Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

python - Search for plural words in line and make it singular words

I want to find if the line consists plural words. If so, I want to change those words to singular words.

For example:

file1.txt

That bananas is yellow. They does taste good.

Expected_output.txt

That banana is yellow. They do taste good.

please help me.

I have tried using .re to delete 's' from the words. But it deletes every 's' in the file. I want to delete only 's' that is at the end of word. For example, 'sacks'. I want 'sack', but I got 'ack'. This is what I have tried.

with open('file1.txt') as file1:
    file1 = file1.read()
test = re.sub('s', ' ', file1)
with open('file1.txt', 'w') as out:
    out.writelines(test)
question from:https://stackoverflow.com/questions/65906547/search-for-plural-words-in-line-and-make-it-singular-words

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You basically have 2 options: nltk library (more complex) or python package with pattern. Neat might be:

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)

Check more here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...