如何逐字阅读文本文件并将这些单词与Python中的现有英语词典进行比较?

问题描述 投票:-1回答:2

我想从给定的文本文件中读取每个单词,然后想要将这些单词与现有的英语词典进行比较,该词典可能是系统词典或任何其他方式。这是我尝试过的代码,但在下面的代码中,存在一个问题。以下代码读取括号或任何其他不必要的字符。

f=open('words.txt')
M=[word for line in f for word in line.split()]
S=list(set(M))

for i in S:
    print i

我该怎么做?

python python-2.7 dictionary nlp word
2个回答
0
投票

您可以使用regex过滤非字母:

import re

M = []
with open('words.txt') as f:
    for line in f.readlines():
        for word in line.split():
            word = re.findall('[A-Za-z]+', word)
            if word:
                M.append(word[0])

S = list(set(M))

for i in S:
    print(i)

输出:

computer
respect
incautiously
softened
satisfied
child
ideas
devoting
overtaken

等等


0
投票

str.strip()函数对您有用。以下代码删除所有圆括号:

f=["sagd  sajdvsja  jsdagjh () shdjkahk sajhdhk (ghj jskldjla) ...."]
M=[word.strip("()") for line in f for word in line.split()]
S=list(set(M))

for i in S:
    print (i)
© www.soinside.com 2019 - 2024. All rights reserved.