将txt文件进行词形还原并仅替换词形还原后的单词。

3

遇到了从txt文件中提取词形的问题。我已经列出了这些单词,但不确定如何在此之后进行词形还原。

以下是我的代码:

import nltk, re
nltk.download('wordnet')
from nltk.stem.wordnet import WordNetLemmatizer

def lemfile():
    f = open('1865-Lincoln.txt', 'r')
    text = f.read().lower()
    f.close()
    text = re.sub('[^a-z\ \']+', " ", text)
    words = list(text.split())

请查看 https://www.kaggle.com/alvations/basic-nlp-with-nltk。 - alvas
请注意“词干提取和词形还原”部分。 - alvas
3个回答

4

初始化一个WordNetLemmatizer对象,并对你的每一行中的单词进行词形还原处理。你可以使用fileinput模块执行就地文件I/O操作。

# https://dev59.com/h2035IYBdhLWcg3wYe8F#5463419
import fileinput

lemmatizer = WordNetLemmatizer()
for line in fileinput.input('1865-Lincoln.txt', inplace=True, backup='.bak'):
    line = ' '.join(
        [lemmatizer.lemmatize(w) for w in line.rstrip().split()]
    )
    # overwrites current `line` in file
    print(line)

fileinput.input会在使用时将标准输出重定向到打开的文件。


这是否意味着我不必像之前那样先列出单词? - ArchivistG
我之前提到的是,所有以“ing”结尾的单词仍然以“ing”结尾,它所做的只是删除一些不需要删除的随机单词末尾的“s”,比如“less”,这样仍然可以保留其词根。 - ArchivistG
1
@ArchivistG 如果你看文档,lemmatize 接受第二个参数,即词性(名词、动词等)。所有单词默认都是名词,因此带有 -ing 的动词不会被词形还原,除非你设置 pos='v'。你可以使用 lemmatizer.lemmatize(lemmatizer.lemmatize(w), pos='v'),但要小心……它很慢。 - cs95
我回家后会尝试一下。现在离开咖啡店了。谢谢! - ArchivistG
1
@ArchivistG 祝你好运!如果你需要更多帮助,随时联系我(虽然我不确定在这一点上我能做些什么:p) - cs95
显示剩余6条评论

0

对文本文件进行词形还原并仅替换词形还原后的单词可以通过以下方式完成--`

import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from pywsd.utils import lemmatize_sentence

lmm = WordNetLemmatizer()
ps = PorterStemmer()

new_data= []

with open('/home/rahul/Desktop/align.txt','r') as f:
f1 = f.read()
f2 = f1.split()
en_stops = set(stopwords.words('english'))
hu_stops = set(stopwords.words('hungarian'))

all_words = f2 
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~[<p>]'''
#if lemmatization of one string is required then uncomment below line
#data='this is coming rahul  schooling met happiness making'
print ()
for line in all_words:
    new_data=' '.join(lemmatize_sentence(line))
    print (new_data)

PS- 根据您的需要进行缩进。 希望这有所帮助!!!


0

您也可以尝试在pywsd包中使用NLTK的WordNetLemmatizer的包装器,具体来说是https://github.com/alvations/pywsd/blob/master/pywsd/utils.py#L129

安装:

pip install -U nltk
python -m nltk.downloader popular
pip install -U pywsd

代码:

>>> from pywsd.utils import lemmatize_sentence
>>> lemmatize_sentence('These are foo bar sentences.')
['these', 'be', 'foo', 'bar', 'sentence', '.']
>>> lemmatize_sentence('These are foo bar sentences running.')
['these', 'be', 'foo', 'bar', 'sentence', 'run', '.']

针对您的问题:

from __future__ import print_function
from pywsd.util import lemmatize_sentence 

with open('file.txt') as fin, open('outputfile.txt', 'w') as fout
    for line in fin:
        print(' '.join(lemmatize_sentence(line.strip()), file=fout, end='\n')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接