How to split each words from several lines of a word file? (python)

前端 未结 3 1384
一整个雨季
一整个雨季 2021-01-28 10:32

I have a text file:

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already          


        
3条回答
  •  旧时难觅i
    2021-01-28 11:13

    I understand what you are trying to achieve. Instead of the way you wrote it, here is a simpler approach:

    import re
    ls=set(re.findall(r"[\w']+", text)) #text is the input
    print(sorted(ls))
    

    Tested it to make sure it works:

    EDIT:

    I modified your code a bit to satisfy your use case.

    fh = open(raw_input("Enter file name: "),'r')
    lst = list()
    for line in fh:
        words = line[:-1].split(" ")
        for word in words:
            if word not in lst:
                lst.append(word)
    print(sorted(lst))
    

    Output:

    Enter file name: file.txt
    ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grie', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
    

    Hope that solves your problem.

提交回复
热议问题