Select some words from an existing file in Python

后端 未结 4 762
南方客
南方客 2021-01-24 02:14

I want to separate the exact words of a text file (text.txt) ending in a certain string by using \'endswith\'. The fact is that my variable

h=[w for w i         


        
相关标签:
4条回答
  • 2021-01-24 02:44

    Open the file first and then process it like this:

    with open('text.txt', 'r') as file:
            content = file.read()
    h=[w for w in content.split() if w.endswith('os')]
    
    0 讨论(0)
  • 2021-01-24 02:45
    f=open('text.txt')
    h=[w for w in f if w.endswith('os')]
    

    This should work properly. Reasons it may be not working for you,

    1. You should strip the line first. There may be hidden ascii chars, like "\n". You can use rstrip() method for that. Something like this.

    h=[w.rstrip() for w in f if w.rstrip().endswith('os')]

    1. After reading the file once, the w pointer reaches the End Of File (EOF), and hence any more read-operations will be in vain. To move the pointer back to the starting of the file, either use seek method, or re-open the file.
    0 讨论(0)
  • 2021-01-24 02:55

    Splitting the seperate words into a list (assuming they are seperated by spaces)

    f = open('text.txt').read().split(' ')
    

    Then to get a list of the words ending in "os", like you had:

    h=[w for w in f if w.endswith('os')]
    
    0 讨论(0)
  • 2021-01-24 03:03
    with open('text.txt') as f:
        words = [word for line in f for word in line.split() if word.endswith('os')]
    

    Your first attempt does not read the file, or even open it. Instead, it loops over the characters of the string 'text.txt' and checks each of them if it ends with 'os'.

    Your second attempt iterates over lines of the file, not words -- that's how a for loop works with a file handle.

    0 讨论(0)
提交回复
热议问题