根据 Python 中的最后两个字符分隔单词



我有一个程序,可以将以a,as,e,es,o,os结尾的葡萄牙语单词分开。我创建了一些列表,我遍历文件并根据它们的结尾将文件中的单词分配到这些不同的列表中。与模式不匹配的单词将分配给名为"其他"的列表。 现在,我想根据最后两个字符分隔所有其他剩余的单词。我想我可以做以前做过的同样的事情:例如,以"em"结尾的单词分配给名为"em"的列表,以"ul"结尾的单词分配给名为"ul"的列表,依此类推。但是,我最终会得到一个巨大的代码,因为我已经检查过并且还有其他 470 个结局!因此,我需要手动创建 470 个列表。有谁知道我如何自动执行此操作?还是任何其他解决问题的方法?到目前为止,我的代码如下。提前非常感谢!!

from nltk.tokenize import sent_tokenize,wordpunct_tokenize
import re
import os
import io
import sys
from pathlib import Path
while True:
try:
file_to_open =Path(input("Please, insert your file path: "))
with open(file_to_open,'r', encoding="utf-8") as f:
words = f.read().lower()
break         
except FileNotFoundError:
print("nFile not found. Better try again")
except IsADirectoryError:
print("nIncorrect Directory path.Try again")
other=[]
e=[]
o=[]
a=[]
for y in words:
if y[-1:] == 'a'or y[-2:]=='as':
a.append(y)
elif y[-1:] == 'o' or y[-2:] =='os' :
o.append(y)
elif y[-1:] == 'e'or y[-2:]=='es':
e.append(y)
else:
other.append(y)
otherendings=[]
for t in other:
endings=t[-2:]
otherendings.append(endings)
print(len(otherendings))
print(set(otherendings)) #470

创建一个词典,其中键是词尾:

word_dict = {}
for word in words:
ending = word[-2:]
try: 
word_dict[ending].append(word)
except:
word_dict[ending] = [word]

在对单词进行迭代之后,您将拥有一个字典,其中键将由两个字母组成的字符串,每个键将包含一个以这两个字母结尾的单词列表。

最新更新