gpt4 book ai didi

python - 如何使用 python 从文本文件中读取行但排除包含特定单词的行

转载 作者:行者123 更新时间:2023-12-01 09:24:54 25 4
gpt4 key购买 nike

我正在尝试制作一个程序来计算用户从文本文件中读取的推文数量。唯一的问题是我需要排除任何带有“DM”或“RT”字样的行。

file = open('stream.txt', 'r')
fileread = file.readlines()
tweets = [string.split() for string in fileread]

如何更改我的代码以确保它排除带有“DM”或“RT”的行?

感谢所有帮助:D

最佳答案

打开文件后请务必将其关闭。最好的方法是使用 with open(...)

答案的解决方案是在列表理解中添加一个条件:

with open('stream.txt', 'r') as file:
fileread = file.readlines()

tweets = [string.split() for string in fileread
if not "DM" in string and not "RT" in string]

如果您想排除多个字符串,可以在某些时候使用 any 来节省空间:

with open('stream.txt', 'r') as file:
fileread = file.readlines()

exclude = ["DM", "RT"]
tweets = [string.split() for string in fileread
if not any(exclude[j] in string for j in range(len(exclude)))]

关于python - 如何使用 python 从文本文件中读取行但排除包含特定单词的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508756/

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