【问题标题】:python re.compile and split with ÆØÅ charcterspython re.compile and split with ÆØÅ 字符
【发布时间】: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 HOWTOJoel 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


【解决方案1】:

修改您的脚本以使用最佳实践:

import csv
import math
import os
import re

LOCATION = os.path.dirname(os.path.abspath(__file__))
afinn_filename = os.path.join(LOCATION, '/AFINN/AFINN-111DK.txt')

pattern_split = re.compile(r"\W+")

with open(afinn_filename, encoding='utf8', newline='') as infile:
    reader = csv.reader(infile, delimiter='\t')
    afinn = {key: int(score) for key, score in reader}


def sentiment(text):
    words = pattern_split.split(text.lower().strip())
    if not words:
        return 0
    sentiments = [afinn.get(word, 0) for word in words]
    return sum(sentiments) / math.sqrt(len(sentiments))


# Print result
text = "ånd ånd med fløde... :)asd "
id = 999
split = "###"
print('{sentiment:6.2f}{split}{id}{split}{text}'.format(
    sentiment=sentiment(text), id=id, split=split, text=text))

使用 Python 3 运行它意味着 text 是一个 Unicode 对象,并且正则表达式使用 re.UNICODE 集进行解释。

在 Python 2 中,您会使用:

text = u"ånd ånd med fløde... :)asd "

(注意字符串前面的 u 前缀)和

pattern_split = re.compile(ur"\W+", re.UNICODE)

您的 AFINN 文件仍将被读取为 CSV,但事后从 UTF8 解码 key,使用:

with open(afinn_filename, 'rb') as infile:
    reader = csv.reader(infile, delimiter='\t')
    afinn = {key.decode('utf8'): int(score) for key, score in reader}

【讨论】:

  • 谢谢。您的示例中有很多错误,所以我使用了 Python 2 的提示。您唯一缺少的是这个小代码:codecs.open(filenameAFINN, "r", "utf-8")
  • @boje:不,我以二进制模式打开文件,然后从 UTF-8 解码,每个字。如果没有输入文件,就很难测试代码,它是即兴写的。我会看看有什么可以修复的。
  • @boje:在那里,清理了愚蠢的语法错误,抱歉。
【解决方案2】:

我想指出我的afinn Python 包,它应该与国际字符集一起使用,包括丹麦语和(某些版本的)Python 2 和 3。有一个英语和丹麦语单词列表。我可能会解决你的问题。

这里是 Python 2.7 或 Python 3.4:

>>> from afinn import Afinn
>>> afinn = Afinn(language='da', emoticons=True)
>>> afinn.score(u"ånd ånd med fløde... :)asd ")
4.0
>>> afinn.score('Hvis ikke det er det mest afskyelige flueknepperi...')
-6.0

你可以在这里获取图书馆:

https://github.com/fnielsen/afinn

或在pip install afinn 的 Python 包索引处

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 2022-12-02
    • 2021-01-07
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多