小编Dav*_*ale的帖子

如何使用python tarfile模块将文件附加到tar文件?

我想在tar文件中附加一个文件.例如,文件test.tar.gza.png, b.png, c.png.我有一个新的名为png文件a.png,我想追加到a.pngtest.tar.gz并覆盖旧的文件a.pngtest.tar.gz.我的代码:

import tarfile
a = tarfile.open('test.tar.gz', 'w:gz')
a.add('a.png')
a.close()
Run Code Online (Sandbox Code Playgroud)

然后,所有文件都test.tar.gz消失但是a.png,如果我将我的代码更改为:

import tarfile
a = tarfile.open('test.tar.gz', 'a:')# or a:gz
a.add('a.png')
a.close()
Run Code Online (Sandbox Code Playgroud)

程序崩溃,错误日志:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/tarfile.py", line 1678, in open
    return func(name, filemode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1705, in taropen
    return cls(name, mode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1588, in __init__ …
Run Code Online (Sandbox Code Playgroud)

python tarfile

13
推荐指数
2
解决办法
3898
查看次数

predict.glm(,type ="terms")实际上做了什么?

我对R作用中的predict.glm函数的方式感到困惑.根据帮助,

"terms"选项返回一个矩阵,给出模型公式中每个项在线性预测器标度上的拟合值.

因此,如果我的模型的形式为f(y)= X*beta,那么命令

predict(model, X, type='terms')
Run Code Online (Sandbox Code Playgroud)

预期产生相同的矩阵X,乘以β元素.例如,如果我训练以下模型

test.data = data.frame(y = c(0,0,0,1,1,1,1,1,1), x=c(1,2,3,1,2,2,3,3,3))
model = glm(y~(x==1)+(x==2), family = 'binomial', data = test.data)
Run Code Online (Sandbox Code Playgroud)

得到的系数是

beta <- model$coef
Run Code Online (Sandbox Code Playgroud)

设计矩阵是

X <- model.matrix(y~(x==1)+(x==2), data = test.data)

  (Intercept) x == 1TRUE x == 2TRUE
1           1          1          0
2           1          0          1
3           1          0          0
4           1          1          0
5           1          0          1
6           1          0          1
7           1          0          0
8           1          0          0
9           1          0          0
Run Code Online (Sandbox Code Playgroud)

然后乘以它应该看起来的系数 …

regression r predict lm glm

6
推荐指数
1
解决办法
2712
查看次数

使用 BeautifulSoup 解析 HTML 时缺少特殊字符和标签

我正在尝试使用解析 HTML 文档BeautifulSoup我正在尝试使用Python

\n\n

但它会停止解析特殊字符,如下所示:

\n\n
from bs4 import BeautifulSoup\ndoc = '''\n<html>\n    <body>\n        <div>And I said \xc2\xabWhat the %&#@???\xc2\xbb</div>\n        <div>some other text</div>\n    </body>\n</html>'''\nsoup = BeautifulSoup(doc,  'html.parser')\nprint(soup)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这段代码应该输出整个文档。相反,它只打印

\n\n
<html>\n<body>\n<div>And I said \xc2\xabWhat the %</div></body></html>\n
Run Code Online (Sandbox Code Playgroud)\n\n

该文件的其余部分显然已丢失。被组合阻止了'&#'

\n\n

问题是,如何设置 BS 或预处理文档,以避免此类问题,但丢失尽可能少的文本(可能提供信息)?

\n\n

我在 Windows 10 上使用版本 4.6.0 的 bs4 和 Python 3.6.1。

\n\n

更新。该方法soup.prettify()不起作用,因为它soup已经损坏了。

\n

python parsing beautifulsoup html-parsing python-3.x

3
推荐指数
1
解决办法
962
查看次数