我正在从Google文档中提取数据,处理数据并将其写入文件(最终我将粘贴到Wordpress页面).
它有一些非ASCII符号.如何将这些安全地转换为可以在HTML源中使用的符号?
目前我正在将所有内容转换为Unicode,在Python字符串中将它们连接在一起,然后执行:
import codecs
f = codecs.open('out.txt', mode="w", encoding="iso-8859-1")
f.write(all_html.encode("iso-8859-1", "replace"))
Run Code Online (Sandbox Code Playgroud)
最后一行有编码错误:
UnicodeDecodeError:'ascii'编解码器无法解码位置12286中的字节0xa0:序数不在范围内(128)
部分解决方案:
这个Python运行时没有错误:
row = [unicode(x.strip()) if x is not None else u'' for x in row]
all_html = row[0] + "<br/>" + row[1]
f = open('out.txt', 'w')
f.write(all_html.encode("utf-8"))
Run Code Online (Sandbox Code Playgroud)
但是如果我打开实际的文本文件,我会看到许多符号,如:
Qur’an
Run Code Online (Sandbox Code Playgroud)
也许我需要写一些文本文件以外的东西?
我正在使用python3.3并且在尝试挑选一个简单的字典时遇到了一个神秘的错误.
这是代码:
import os
import pickle
from pickle import *
os.chdir('c:/Python26/progfiles/')
def storvars(vdict):
f = open('varstor.txt','w')
pickle.dump(vdict,f,)
f.close()
return
mydict = {'name':'john','gender':'male','age':'45'}
storvars(mydict)
Run Code Online (Sandbox Code Playgroud)
我得到:
Traceback (most recent call last):
File "C:/Python26/test18.py", line 31, in <module>
storvars(mydict)
File "C:/Python26/test18.py", line 14, in storvars
pickle.dump(vdict,f,)
TypeError: must be str, not bytes
Run Code Online (Sandbox Code Playgroud) 我一直在寻找一种从python脚本运行外部进程的方法,并在执行期间打印其stdout消息.
下面的代码可以工作,但在运行时打印没有stdout输出.当它退出时,我收到以下错误:
sys.stdout.write(nextline)TypeError:必须是str,而不是bytes
p = subprocess.Popen(["demo.exe"],stdout = subprocess.PIPE, stderr= subprocess.PIPE)
# Poll process for new output until finished
while True:
nextline = p.stdout.readline()
if nextline == '' and p.poll() != None:
break
sys.stdout.write(nextline)
sys.stdout.flush()
output = p.communicate()[0]
exitCode = p.returncode
Run Code Online (Sandbox Code Playgroud)
我使用的是python 3.3.2
我正在使用Gmail API访问我的Gmail数据和google python api客户端.
根据获取消息附件的文档,他们为python提供了一个示例
https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get
但我尝试相同的代码然后我收到错误:
AttributeError: 'Resource' object has no attribute 'user'
Run Code Online (Sandbox Code Playgroud)
我遇到错误的地方:
message = service.user().messages().get(userId=user_id, id=msg_id).execute()
Run Code Online (Sandbox Code Playgroud)
所以我试着users()替换user()
message = service.users().messages().get(userId=user_id, id=msg_id).execute()
Run Code Online (Sandbox Code Playgroud)
但我没有part['body']['data']进去for part in message['payload']['parts']
如何在Python 3中将网站的源代码复制到文本文件中?
编辑:为了澄清我的问题,这就是我所拥有的:
import urllib.request
def extractHTML(url):
f = open('temphtml.txt', 'w')
page = urllib.request.urlopen(url)
pagetext = page.read()
f.write(pagetext)
f.close()
extractHTML('http:www.google.com')
Run Code Online (Sandbox Code Playgroud)
我得到f.write()函数的以下错误:
builtins.TypeError: must be str, not bytes
Run Code Online (Sandbox Code Playgroud)