gpt4 book ai didi

python - 从文件中删除单词

转载 作者:行者123 更新时间:2023-11-28 16:46:55 24 4
gpt4 key购买 nike

我正在尝试获取一个常规文本文件并删除在一个单独的文件(停用词)中标识的单词,该文件包含要删除的单词,由回车符(“\n”)分隔。

现在我正在将这两个文件转换成列表,以便可以比较每个列表的元素。我可以使用此功能,但它不会删除我在停用词文件中指定的所有单词。非常感谢任何帮助。

def elimstops(file_str): #takes as input a string for the stopwords file location
stop_f = open(file_str, 'r')
stopw = stop_f.read()
stopw = stopw.split('\n')
text_file = open('sample.txt') #Opens the file whose stop words will be eliminated
prime = text_file.read()
prime = prime.split(' ') #Splits the string into a list separated by a space
tot_str = "" #total string
i = 0
while i < (len(stopw)):
if stopw[i] in prime:
prime.remove(stopw[i]) #removes the stopword from the text
else:
pass
i += 1
# Creates a new string from the compilation of list elements
# with the stop words removed
for v in prime:
tot_str = tot_str + str(v) + " "
return tot_str

最佳答案

这是使用生成器表达式的替代解决方案。

tot_str = ' '.join(word for word in prime if word not in stopw)

为了提高效率,使用 stopw = set(stopw)stopw 转换为 set

如果 sample.txt 不仅仅是一个空格分隔的文件,您当前的方法可能会遇到问题,例如,如果您有带标点符号的普通句子,那么按空格拆分会将标点符号保留为单词的一部分。要解决此问题,您可以使用 re 模块在空格或标点符号上拆分字符串:

import re
prime = re.split(r'\W+', text_file.read())

关于python - 从文件中删除单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13015956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com