我很难对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']
如果I 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']
如有任何解决问题的建议,我们将不胜感激
谢谢你
您的Unicode字符串列表是正确的。打印列表时,列表中的项目显示为它们的
repr()
函数。打印项目本身时,项目显示为其str()
函数。它只是一个显示选项,类似于将整数打印为十进制或十六进制。你知道吗因此,如果你想正确地看到这些单词,就把它们打印出来,但是为了比较,内容是正确的。你知道吗
值得注意的是,python3改变了
repr()
的行为,现在如果终端直接支持非ASCII字符,并且ascii()
函数再现了python2repr()
的行为,那么它将显示不带转义码的非ASCII字符。你知道吗你可以试试看
打印('['+','.join(Allwords)+']')
相关问题 更多 >
编程相关推荐