【问题标题】:How to encode a python list如何编码 python 列表
【发布时间】:2016-06-16 04:27:15
【问题描述】:

我在尝试对 python 列表进行编码时遇到了困难,我已经使用文本文件进行了编码,以便使用 re 模块计算其中的特定单词。

这是代码:

# encoding text file
with codecs.open('projectsinline.txt', 'r', encoding="utf-8") as f:
    for line in f:
        # Using re module to extract specific words
        unicode_pattern = re.compile(r'\b\w{4,20}\b', re.UNICODE)
        result = unicode_pattern.findall(line)
    word_counts = Counter(result) # It creates a dictionary key and wordCount
    Allwords = []
    for clave in word_counts:
        if word_counts[clave] >= 10: # We look for the most repeated words
            word = clave
            Allwords.append(word)
    print Allwords

部分输出如下所示:

[...u'recursos', u'Partidos', u'Constituci\xf3n', u'veh\xedculos', u'investigaci\xf3n', u'Pol\xedticos']

如果我print 变量word 输出看起来应该是这样。但是,当我使用append 时,所有单词都会再次中断,就像之前的示例一样。

我用这个例子:

[x.encode("utf-8") for x in Allwords]

输出看起来和以前完全一样。

我也用这个例子:

Allwords.append(str(word.encode("utf-8")))

输出发生变化,但单词看起来不应该是:

[...'recursos', 'Partidos', 'Constituci\xc3\xb3n', 'veh\xc3\xadculos', 'investigaci\xc3\xb3n', 'Pol\xc3\xadticos']

一些答案​​已经给出了这个例子:

print('[' + ', '.join(Allwords) + ']')

输出如下:

[...recursos, Partidos, Constitución, vehículos, investigación, Políticos]

说实话我不想打印列表,只是对其进行编码,以便识别所有项目(单词)。

我正在寻找这样的东西:

[...'recursos', 'Partidos', 'Constitución', 'vehículos', 'investigación', 'Políticos']

感谢任何解决问题的建议

谢谢,

【问题讨论】:

  • 字不断;它们只是以原始格式显示。 list 使用 __repr__() 获取其元素的字符串值。
  • 有没有办法在列表中显示带有重音符号的单词?
  • 有点。你可以做print("[" + ", ".join(Allwords) + "]")
  • 它改变了输出,但我得到了这个:[...recursos, Partidos, Constitución, vehículos, investigación, Políticos]
  • 好吧,对不起;我不知道如何帮助你。为什么要将其打印为列表?

标签: python regex python-2.7 encoding utf-8


【解决方案1】:

你可能会尝试什么

print('[' + ', '.join(Allwords) + ']')

【讨论】:

  • 谢谢,@cxad。使用该示例,我得到了[...recursos, Partidos, Constitución, vehículos, investigación, Políticos] 另一方面,我不想打印列表,只需对其进行编码,以便识别所有项目。
【解决方案2】:

您的 Unicode 字符串列表是正确的。当您打印列表时,列表中的项目显示为它们的repr() 函数。当您打印项目本身时,项目将显示为它们的str() 函数。它只是一个显示选项,类似于将整数打印为十进制或十六进制。

因此,如果您想正确查看单个单词,请打印它们,但为了比较,内容是正确的。

值得注意的是,Python 3 改变了 repr() 的行为,现在如果终端直接支持非 ASCII 字符而不使用转义码,并且 ascii() 函数再现了 Python 2 的 repr() 行为。

【讨论】:

  • 谢谢,@MarkTolonen!有时很难解释主要问题是什么。我正在学习,所以很难弄清楚所有的概念。当我想将一个列表中的每个项目与另一个列表中的项目进行比较时,就会出现我的代码问题。因此,如果我比较项目 social 一切正常,但是当我比较 Constitución 时,代码无法识别该项目,因此它会跳过该项目。
  • 问题出在文本文件中。我将格式从 UTF-8 更改为 ANSI。现在不仅可以显示项目,而且可以识别每个项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
  • 2015-02-27
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多