【问题标题】:Messing up my unicode output - but where and how?弄乱我的 unicode 输出 - 但在哪里以及如何?
【发布时间】:2016-07-15 16:41:19
【问题描述】:

我正在对一些文本文件进行字数统计,并将结果存储在字典中。我的问题是,在输出到文件后,即使它们在原始文本中也不能正确显示。 (我使用 TextWrangler 来查看它们)。 例如,破折号在原始文件中显示为破折号,但在输出中显示为 \u2014;在输出中,每个单词也以 u 为前缀。

问题

我不知道在我的脚本中发生这种情况的地点、时间和方式。

我正在使用codecs.open() 读取文件,并使用codecs.open()json.dump() 输出它们。他们都以同样的方式出错。在这两者之间,所有要做的就是

  1. 标记化

  2. 正则表达式

  3. 查字典

而且我不知道我在哪里搞砸了;我已停用标记化和大多数其他功能,但没有效果。这一切都发生在 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


    【解决方案1】:

    由于您的示例是部分伪代码,因此无法运行真正的测试并为您提供可以运行并经过测试的东西,但是通过阅读您提供的内容,我认为您可能会误解 Unicode 在 Python 2 中的工作方式。

    unicode 类型(例如通过unicode()unichr() 函数生成)是Unicode 字符串的内部表示,可用于字符串操作和比较目的。它没有关联的编码。 unicode() 函数将缓冲区作为其第一个参数,将编码作为其第二个参数,并使用该编码解释该缓冲区以生成一个内部可用的 Unicode 字符串,该字符串从那时起不受编码的影响。

    该 Unicode 字符串并不意味着要写入文件;所有文件格式都假定某种编码,并且您应该在将该 Unicode 字符串写入文件之前再次提供一种编码。每个地方都有像 unicode(fileno)unicode(k)unicode(i) 这样的构造是可疑的,因为您依赖于默认编码(这可能不是您想要的),并且因为您将继续公开大部分这些值直接保存到文件系统中。

    处理完这些 Unicode 字符串后,您可以对它们使用内置方法 encode(),并将所需的编码作为参数,将它们打包成编码所需的普通字节字符串。

    回顾你上面的例子,你的inputtext 变量是一个普通的字符串,其中包含根据 UTF-8 编码编码的数据。这不是 Unicode。您可以使用inputuni = unicode(inputtext, 'utf-8') 之类的操作将其转换为 Unicode 字符串,并根据您的选择对其进行操作,但对于您正在做的事情,您甚至可能觉得没有必要。如果您确实将其转换为 Unicode,尽管您必须对您计划写入文件的任何 Unicode 字符串执行相当于 inputuni.encode('UTF-8') 的操作。

    【讨论】:

    • 感谢您的详细回答,我确实弄错了unicode() 的作用!同时我做了一些测试,看起来主要问题是我的输出功能——我已经相应地编辑了我的问题。感谢您对此进行调查!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2023-03-28
    • 1970-01-01
    • 2013-01-29
    • 2023-03-03
    • 2017-06-14
    • 1970-01-01
    相关资源
    最近更新 更多