Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - Print values from list based from separate text file

How do I print a list of words from a separate text file? I want to print all the words unless the word has a length of 4 characters.

words.txt file looks like this:

abate chicanery disseminate gainsay latent aberrant coagulate dissolution garrulous laud

It has 334 total words in it. I'm trying to display the list until it reaches a word with a length of 4 and stops.

wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()

#List outputs length of words in list

lengths= [len(i) for i in wordList]
for i in range(10):
    if i >= len(lengths):
         break
    print(lengths[i], end = ' ')

# While loop displays names based on length of words in list

while words != 4:
    if words in wordList:
        print("
Selected words are:", words)
    break

output

5 9 11 7 6 8 9 11 9 4

sample desired output

Selected words are:

Abate

Chicanery

disseminate

gainsay

latent

aberrant

coagulate

dissolution

garrulous

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given that you only want the first 10 words. There isn't much point reading all 4 lines. You can safely read just the 1st and save yourself some time.

#from itertools import chain

with open('words.txt') as f:

    # could raise `StopIteration` if file is empty
    words = next(f).strip().split()

    # to read all lines
    #words = []
    #for line in f:
    #    words.extend(line.strip().split())

    # more functional way
    # words = list(chain.from_iterable(line.strip().split() for line in f))

print("Selected words are:")
for word in words[:10]:
    if len(word) != 4:
        print(word)

There are a few alternative methods I left in there but commented out.

Edit using a while loop.

i = 0
while i < 10:
    if len(words[i]) != 4:
        print(words[i])
    i += 1

Since you know how many iterations you can do, you can hide the mechanics of the iteration using a for loop. A while does not facilitate this very well and is better used when you don't know how many iterations you will do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...