How would I read only the first word of each line of a text file?

前端 未结 6 1249
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 22:17

I wanted to know how I could read ONLY the FIRST WORD of each line in a text file. I tried various codes and tried altering codes but can only manage to read whole lines from a

6条回答
  •  一整个雨季
    2021-02-04 23:18

    Changed to a one-liner that's also more efficient with the strip as Jon Clements suggested in a comment.

    with open('Quizzes.txt', 'r') as f:
        wordlist = [line.split(None, 1)[0] for line in f]
    

    This is pretty irrelevant to your question, but just so the line.split(None, 1) doesn't confuse you, it's a bit more efficient because it only splits the line 1 time.

    From the str.split([sep[, maxsplit]]) docs

    If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

    ' 1 2 3 '.split() returns ['1', '2', '3']

    and

    ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].

提交回复
热议问题