如何计算 Python 中文本文件中的单词(以及带重音符号的单词!)?

How to count words (and also those with accents !) in a text file in Python?

我想在 Python 中编写一个脚本,将 file.txt 作为输入,然后 return 我会得到一个按频率排序的单词列表。 我的问题是我的文本是法语的,因此像 "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 变成 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]