【发布时间】:2013-05-14 17:20:39
【问题描述】:
我是 Python 的新手。 我确实有一个包含单词列表的文件。它们包含丹麦字母 (ÆØÅ) 但 re.compile 不理解这些字符。该函数按每个 ÆØÅ 拆分单词。文本从 Twitter 和 Facebook 下载,并不总是只包含字母。
text = "Rød grød med fløde.... !! :)"
pattern_split = re.compile(r"\W+")
words = pattern_split.split(text.lower())
words = ['r', 'd', 'gr', 'd', 'med', 'fl', 'de']
正确的结果应该是
words = ['rød', 'grød', 'med', 'fløde']
如何获得正确的结果?
完整代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
import math, re, sys, os
reload(sys)
sys.setdefaultencoding('utf-8')
# AFINN-111 is as of June 2011 the most recent version of AFINN
#filenameAFINN = 'AFINN/AFINN-111.txt'
# Get location of file
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
filenameAFINN = __location__ + '/AFINN/AFINN-111DK.txt'
afinn = dict(map(lambda (w, s): (w, int(s)), [
ws.strip().split('\t') for ws in open(filenameAFINN) ]))
# Word splitter pattern
pattern_split = re.compile(r"\W+")
#pattern_split = re.compile('[ .,:();!?]+')
def sentiment(text):
print(text)
words = pattern_split.split(text.lower().strip())
print(words)
sentiments = map(lambda word: afinn.get(word, 0), words)
if sentiments:
sentiment = float(sum(sentiments))/math.sqrt(len(sentiments))
else:
sentiment = 0
return sentiment
# Print result
text = "ånd ånd med fløde... :)asd "
id = 999
split = "###"
print("%6.2f%s%s%s%s" % (sentiment(text), split, id, split, text))
【问题讨论】:
-
你真的很想了解Unicode,编码和解码,然后使用
re.UNICODE打开正则表达式中的unicode支持。请参阅 Python Unicode HOWTO 和 Joel on Software on Unicode。 -
(在 Python 3 中工作,所以我添加了 Python 2 标签)
-
@Wooble:完全正确,因为在 Py3 中示例字符串是 Unicode,正则表达式也是。
-
当更改为 Python 3.3 时,我在 "lamdba" afinn = dict(map(lambda (w, s): (w, int(s)), [ ws.strip() .split('\t') for ws in open(filenameAFINN) ]))
-
@boje:Python 3 对在参数中使用元组有限制(不允许)。
标签: python regex split python-2.x