我正在使用PorterStemmer
Python端口
Porter词干算法(或"Porter-stemmer")是一个从英语单词中去除常见词形和屈折词尾的过程。它的主要用途是作为术语规范化过程的一部分,通常在设置信息检索系统时进行。
对于以下内容。。
您需要做的另一件事是将每个单词缩减为词干。例如,单词
sing
、sings
、singing
均具有相同的茎,即sing
。有一种被合理接受的方法可以做到这一点,它被称为波特算法。你可以从下载执行它的东西http://tartarus.org/martin/PorterStemmer/.
我已经修改了代码。。
if __name__ == '__main__':
p = PorterStemmer()
if len(sys.argv) > 1:
for f in sys.argv[1:]:
infile = open(f, 'r')
while 1:
output = ''
word = ''
line = infile.readline()
if line == '':
break
for c in line:
if c.isalpha():
word += c.lower()
else:
if word:
output += p.stem(word, 0,len(word)-1)
word = ''
output += c.lower()
print output,
infile.close()
从经过预处理的字符串中读取input
而不是文件并返回输出。
def algorithm(input):
p = PorterStemmer()
while 1:
output = ''
word = ''
if input == '':
break
for c in input:
if c.isalpha():
word += c.lower()
else:
if word:
output += p.stem(word, 0,len(word)-1)
word = ''
output += c.lower()
return output
请注意,如果我将return output
放置在与while 1:
相同的缩进上,它将变为infinite loop
。
用法(示例)
import PorterStemmer as ps
ps.algorithm("Michael is Singing");
输出
Michael是
预期输出
迈克尔是新
我做错了什么?
因此,看起来罪魁祸首是它当前没有将输入的最后部分写入output
(例如,尝试"Michael正在唱歌"-它应该正确地写入所有内容并省略"stuff")。可能有一种更优雅的方法来处理这个问题,但有一件事你可以尝试,那就是在for
循环中添加一个else
子句。由于问题是output
中没有包含最终单词,我们可以使用else
来确保在for
循环完成时添加最终单词:
def algorithm(input):
print input
p = PorterStemmer()
while 1:
output = ''
word = ''
if input == '':
break
for c in input:
if c.isalpha():
word += c.lower()
elif word:
output += p.stem(word, 0,len(word)-1)
word = ''
output += c.lower()
else:
output += p.stem(word, 0, len(word)-1)
print output
return output
这已经用两个测试案例进行了广泛的测试,所以很明显它是防弹的:)可能有一些边缘案例在那里爬来爬去,但希望它能让你开始。