python - 使用 Python 将文本文件中的复数转换为单数

标签 python text stemming plural singular

我有这样的 txt 文件:

word, 23
Words, 2
test, 1
tests, 4

我希望它们看起来像这样:

word, 23
word, 2
test, 1
test, 4

我希望能够在 Python 中获取一个 txt 文件并将复数单词转换为单数。这是我的代码:

import nltk

f = raw_input("Please enter a filename: ")

def openfile(f):
    with open(f,'r') as a:
       a = a.read()
       a = a.lower()
       return a

def stem(a):
    p = nltk.PorterStemmer()
    [p.stem(word) for word in a]
    return a

def returnfile(f, a):
    with open(f,'w') as d:
        d = d.write(a)
    #d.close()

print openfile(f)
print stem(openfile(f))
print returnfile(f, stem(openfile(f)))

我还尝试了这两个定义而不是 stem 定义:

def singular(a):
    for line in a:
        line = line[0]
        line = str(line)
        stemmer = nltk.PorterStemmer()
        line = stemmer.stem(line)
        return line

def stem(a):
    for word in a:
        for suffix in ['s']:
            if word.endswith(suffix):
                return word[:-len(suffix)]
            return word

之后,我想采用重复的单词(例如 testtest)并通过将它们旁边的数字相加来合并它们。例如:

word, 25
test, 5

我不知道该怎么做。一个解决方案会很好,但不是必需的。

最佳答案

如果你有复杂的单词要单数化,我不建议你使用词干提取,而是使用合适的 python 包链接 pattern :

from pattern.text.en import singularize

plurals = ['caresses', 'flies', 'dies', 'mules', 'geese', 'mice', 'bars', 'foos',
           'families', 'dogs', 'child', 'wolves']

singles = [singularize(plural) for plural in plurals]
print(singles)

返回:

>>> ['caress', 'fly', 'dy', 'mule', 'goose', 'mouse', 'bar', 'foo', 'foo', 'family', 'family', 'dog', 'dog', 'child', 'wolf']

它并不完美,但它是我发现的最好的。 96% 基于文档:http://www.clips.ua.ac.be/pages/pattern-en#pluralization

关于python - 使用 Python 将文本文件中的复数转换为单数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31387905/

相关文章:

Python - 如何获取在我的计算机上运行的服务

python - 如何在 GIT 中处理 python 模块

excel - 如何将文本导入时间格式?

lucene.net - Lucene.NET 中的英语词干或词形还原,无需 SnowBall 分析器或自定义分析器

python - Python 中的 is 运算符

python - "SyntaxError: non-default argument follows default argument"的含义

apache-flex - 如何在 AS3 中从文本创建粒子结构?

c - 为什么我的字典没有正确计算出现次数?

nlp - 从词干中获取单词(词干提取)

algorithm - 波特词干分析器,步骤 1b