简体   繁体   中英

Finding the last word in every sentence in a txt file

So I have a text file that has tweets in it.

I need to only print the last word in every line that is 8 or more characters and doesn't have # : or @ in the word.

Currently, I can find all the words in the text file that fulfils those requirements except only printing the last word in the sentence. So if a line that contains multiple words that fulfil the requirements I print all the words

This is how far I am currently

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)

The output is:

Candidates
remained
candidates
finished
Watching
couldn't
hangover
disappointing.

but should be:

remained
finished
couldn't
hangover
disappointing.

Any help is appreciated

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]访问这个列表中的最后一个元素,然后在每一行中对这个词应用你的规则。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM