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

前端 未结 6 1247
佛祖请我去吃肉
佛祖请我去吃肉 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:17

    I'd go for the str.split and similar approaches, but for completness here's one that uses a combination of mmap and re if you needed to extract more complicated data:

    import mmap, re
    
    with open('quizzes.txt') as fin:
        mf = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
        wordlist = re.findall('^(\w+)', mf, flags=re.M)
    

提交回复
热议问题