特别是从这个 getwords 函数中删除停止字母时。
def getwords(fileName):
file = open(fileName, 'r')
text = file.read()
stopletters = [".", ",", ";", ":", "'s", '"', "!", "?", "(", ")", '“', '”']
text = text.lower()
for letter in stopletters:
text = text.replace(letter, "")
words = text.split()
return words
对于这个双字母函数中的循环
def compute_bigrams(fileName):
input_list = getwords(fileName)
bigram_list = {}
for i in range(len(input_list) - 1):
if input_list[i] in bigram_list:
bigram_list[input_list[i]] = bigram_list[input_list[i]] + [input_list[i + 1]]
else :
bigram_list[input_list[i]] = [input_list[i + 1]]
return bigram_list
最佳答案
你可以这样重写它:
def getwords(file_name):
with open(file_name, 'r') as file:
text = file.read().lower()
stop_letters = (".", ",", ";", ":", "'s", '"', "!", "?", "(", ")", '“', '”')
text = ''.join([letter if letter not in stop_letters else '' for letter in text])
words = text.split()
return words
我使用上下文管理器打开文件,合并一些行(不需要为 .lower()
设置特殊的行)并使用列表理解来遍历文本并添加字母,但前提是字母不在 stop_letters
中。加入该列表后,您会得到相同的结果。
请注意,您也可以使用生成器表达式,这会更好:
text = ''.join((letter if letter not in stop_letters else '' for letter in text))
如果你真的想保存那一行,你可以这样做:
返回 text.split()
关于python - 如何修改我的函数以使用列表理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59229469/