【问题标题】:How to count words (and also those with accents !) in a text file in Python?如何在 Python 的文本文件中计算单词(以及带有重音符号的单词!)?
【发布时间】:2015-07-29 05:58:50
【问题描述】:

我想用 Python 编写一个脚本,它以 file.txt 作为输入,并返回一个按频率排序的单词列表。 我的问题是我的文本是法语的,因此像“préchauffer”这样的词在我的以下脚本中被计算得很奇怪(见下文),这是有问题的。

from collections import Counter
import re
from re import split
import io

def format_print(counter):
    lst = counter.items()
    lst.sort(key=lambda (a, b): (b, a))
    for word, count in lst:
        print "%-16s | %16d" % (word, count)

def count_words(filename):
    stop_words = frozenset(['le', 'la', 'des', 'et', 'des', 'dans', 'les', 'de', 'une', 'un',
     'se', 'sa'])
    text = io.open(filename, 'r', encoding='utf8').read()
    words = re.findall(r'\w+', text)
    cap_words = [word.upper() for word in words if word not in stop_words and len(word) > 1]
    word_counts = Counter(cap_words)
    return word_counts

format_print(count_words("extract.txt"))

删除我的 file.txt 中的所有重音符号是没有问题的,但我还没有找到这样做的方法。 非常感谢您的帮助

示例文字

étourdi, etourdi, étourdi, préchauffer

上述文字的结果:

CHAUFFER         |                1
ETOURDI          |                1
PR               |                1
TOURDI           |                2

我的预期结果(为简洁起见,此处未格式化)将是

  • 最好的一个:ÉTOURDI 2, ETOURDI 1, PRÉCHAUFFER 1(确实感谢 Burhan Khalid 的评论,“salé”和“sale”有不同的含义,区分它们会很有用)
  • “好的”之一:ETOURDI 3, PRECHAUFFER 1

【问题讨论】:

  • 您确定要这样做吗? salésale 在法语中是两个不同的东西。
  • this
  • @Burhan Khalid,感谢您的评论,确实最好区分这些词。

标签: python diacritics


【解决方案1】:

如果你想规范化重读的字符串(比如:étourdi 变成 etourdi),你可以使用非常好的unidecode 模块。

例子:

text = u'étourdi, etourdi, étourdi, préchauffer'
words = re.findall(r'\w+', text, re.U)
cap_words = [unidecode.unidecode(word).upper() for word in words]

【讨论】:

    猜你喜欢
    • 2014-11-04
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多