【发布时间】:2016-07-15 16:41:19
【问题描述】:
我正在对一些文本文件进行字数统计,并将结果存储在字典中。我的问题是,在输出到文件后,即使它们在原始文本中也不能正确显示。 (我使用 TextWrangler 来查看它们)。 例如,破折号在原始文件中显示为破折号,但在输出中显示为 \u2014;在输出中,每个单词也以 u 为前缀。
问题
我不知道在我的脚本中发生这种情况的地点、时间和方式。
我正在使用codecs.open() 读取文件,并使用codecs.open() 和json.dump() 输出它们。他们都以同样的方式出错。在这两者之间,所有要做的就是
标记化
正则表达式
查字典
而且我不知道我在哪里搞砸了;我已停用标记化和大多数其他功能,但没有效果。这一切都发生在 Python 2 中。 根据之前的建议,我尝试将脚本中的所有内容都保留为 Unicode。
这是我所做的(省略不相关的代码):
#read in file, iterating over a list of "fileno"s
with codecs.open(os.path.join(dir,unicode(fileno)+".txt"), "r", "utf-8") as inputfili:
inputtext=inputfili.read()
#process the text: tokenize, lowercase, remove punctuation and conjugation
content=regular expression to extract text w/out metadata
contentsplit=nltk.tokenize.word_tokenize(content)
text=[i.lower() for i in contentsplit if not re.match(r"\d+", i)]
text= [re.sub(r"('s|s|s's|ed)\b", "", i) for i in text if i not in string.punctuation]
#build the dictionary of word counts
for word in text:
dicti[word].append(word)
#collect counts for each word, make dictionary of unique words
dicti_nos={unicode(k):len(v) for k,v in dicti.items()}
hapaxdicti= {k:v for k,v in perioddicti_nos.items() if v == 1}
#sort the dictionary
sorteddict=sorted(dictionary.items(), key=lambda x: x[1], reverse=True)
#output the results as .txt and json-file
with codecs.open(file_name, "w", "utf-8") as outputi:
outputi.write("\n".join([unicode(i) for i in sorteddict]))
with open(file_name+".json", "w") as jsonoutputi:
json.dump(dictionary, jsonoutputi, encoding="utf-8")
编辑:解决方案
看来我的主要问题是以错误的方式写入文件。如果我将我的代码更改为下面复制的内容,事情就会解决。看起来加入 (string, number) 元组列表将字符串部分弄乱了;如果我先加入元组,一切都会奏效。
对于 json 输出,我必须更改为 codecs.open() 并将 ensure_ascii 设置为 False。显然只是将encoding 设置为utf-8 并没有像我想的那样成功。
with codecs.open(file_name, "w", "utf-8") as outputi:
outputi.write("\n".join([":".join([i[0],unicode(i[1])]) for i in sorteddict]))
with codecs.open(file_name+".json", "w", "utf-8") as jsonoutputi:
json.dump(dictionary, jsonoutputi, ensure_ascii=False)
感谢您的帮助!
【问题讨论】:
标签: python file-io unicode encoding nltk