次のような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)))
定義の代わりに、次の 2 つの定義も試しました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
test
その後、重複した単語 (たとえばand test
) を取得し、それらの横にある数字を合計してそれらをマージしたいと思います。例えば:
word, 25
test, 5
どうすればいいのかわかりません。解決策があればいいのですが、必須ではありません。