0

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.

My code so far:

sentences = []

with open("txt.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

Thank you!

Frorayz
  • 13
  • 5
  • when reading the file, you can limit the reading to 10 lines by doing. `for _ in range(10): line = file.readline()` –  Jun 02 '22 at 15:22
  • Short answer: [use slices](https://stackoverflow.com/questions/509211/understanding-slicing). – jrd1 Jun 02 '22 at 15:23
  • you can use slices as suggested by @jrd1. `sentences[:10]` will give you the first 10 sentences. You can also use `enumerate` when reading the file, or just the old method of starting an index to 0 and checking `if index>=10` to break the loop –  Jun 02 '22 at 15:27
  • put a condition inside the loop. `if index >= 10: break` then outside he conditional you have to increase the index at each iteration. `index += 1` –  Jun 02 '22 at 15:45
  • as what @SembeiNorimaki said, add a break. You can also do `data = list(file)` then `for i in data[:10]` – thethiny Jun 02 '22 at 15:46
  • I added an answer with the different options you have. if you dont want to use a break, put the actions inside a condition –  Jun 02 '22 at 15:51

2 Answers2

0

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)
0

just change your code like this, it should help:

for line in sentences:
    if word in line:
        if count < 10: print(line) # <--------
        count += 1
SergFSM
  • 1,419
  • 1
  • 4
  • 7