[英]Finding the last word in every sentence in a txt file
所以我有一个包含推文的文本文件。
我只需要在 8 个或更多字符的每一行中打印最后一个单词,并且单词中没有 # : 或 @ 。
目前,我可以在文本文件中找到满足这些要求的所有单词,除了只打印句子中的最后一个单词。 因此,如果一行包含满足要求的多个单词,我将打印所有单词
这是我目前的距离
for line in open("tweets.txt"):
line_strip = line.strip()
for word in line_strip.split():
if len(word) >=8 and "#" not in word and ":" not in word and "@" not in word:
print(word)
输出是:
Candidates
remained
candidates
finished
Watching
couldn't
hangover
disappointing.
但应该是:
remained
finished
couldn't
hangover
disappointing.
任何帮助表示赞赏
for line in open("tweets.txt"):
line_strip = line.strip()
words = [word for word in line_strip.split() if len(word) >=8 and "#" not in word and ":" not in word and "@" not in word]
if len(words)>0:
print(words[-1])
line_strip.split()
会给你一个列表,你可以用your_list[-1]
访问这个列表中的最后一个元素,然后在每一行中对这个词应用你的规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.