I am trying to achieve:
- User input word, and it outputs how many lines contain that word also sees it up to the first ten such lines. If no lines has the words, then your program must output
Not found.
in my assignment.
My code so far:
sentences = []
with open("alice.txt") as file:
for line in file:
words = line.split()
words_count = len(words)
if len(words) > len(maxlines.split()):
maxlines = line
sentences.append(line)
word = input("Enter word: ")
count = 0
for line in sentences:
if word in line:
print(line)
count = 1
print(count, "lines contain", word)
if count == 0:
print("Not found.")
How would I only print first 10 line regardless the amount of lines in the file using only: for loops, file operations, len, <, >, >=, <=, ==, append?
Output should look something like this:
Enter word: Alice
Alice was beginning to get very tired of sitting by her sister
thought Alice `without pictures or conversation?'
There was nothing so VERY remarkable in that; nor did Alice
POCKET, and looked at it, and then hurried on, Alice started to
In another moment down went Alice after it, never once
and then dipped suddenly down, so suddenly that Alice had not a
`Well!' thought Alice to herself, `after such a fall as this, I
you see, Alice had learnt several things of this sort in her
or Longitude I've got to?' (Alice had no idea what Latitude was,
Down, down, down. There was nothing else to do, so Alice soon
392 lines contain Alice
Thank you!
CodePudding user response:
If you want to iterate 10 times (old style, not pythonic at all)
index = 0
for line in file:
if index >= 10:
break
# do stuff 10 times
index = 1
Without using break, just put the stuff inside the condition. Notice that the loop will continue iterating, so this is not really a smart solution.
index = 0
for line in file:
if index < 10:
# do stuff 10 times
index = 1
However this is not pythonic at all. the way you should do it in python is using range.
for _ in range(10):
# do stuff 10 times
_ means you don't care about the index and just want to repeat 10 times.
If you want to iterate over file and keeping the index (line number) you can use enumerate
for lineNumber, line in enumerate(file):
if lineNumber >= 10:
break
# do stuff 10 times
Finally as@jrd1 suggested, you can actually read all the file and then only slice the part that you want, in your case
sentences[:10] # will give you the 10 first sentences (lines)
CodePudding user response:
just change your code like this, it should help:
for line in sentences:
if word in line:
if count < 10: print(line) # <--------
count = 1