【发布时间】: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