我正在努力實作:
- 用戶輸入單詞,它會輸出包含該單詞的行數,并且最多可以看到前十行。如果沒有行有這些詞,那么你的程式必須輸出
Not found.
在我的任務中。
到目前為止我的代碼:
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.")
無論檔案中的行數如何,我如何只列印前 10 行:for 回圈、檔案操作、len、<、>、>=、<=、==、追加?
輸出應如下所示:
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
謝謝!
愛麗絲.txt
uj5u.com熱心網友回復:
如果你想迭代 10 次(老風格,根本不是 Pythonic)
index = 0
for line in file:
if index >= 10:
break
# do stuff 10 times
index = 1
不使用中斷,只需將內容放入條件中。請注意,回圈將繼續迭代,因此這并不是一個真正的智能解決方案。
index = 0
for line in file:
if index < 10:
# do stuff 10 times
index = 1
然而,這根本不是pythonic。你應該在 python 中這樣做的方式是使用范圍。
for _ in range(10):
# do stuff 10 times
_ 表示你不關心索引,只想重復 10 次。
如果您想遍歷檔案并保留索引(行號),您可以使用enumerate
for lineNumber, line in enumerate(file):
if lineNumber >= 10:
break
# do stuff 10 times
最后正如@jrd1 建議的那樣,您實際上可以讀取所有檔案,然后根據您的情況只切片您想要的部分
sentences[:10] # will give you the 10 first sentences (lines)
uj5u.com熱心網友回復:
只需像這樣更改您的代碼,它應該會有所幫助:
for line in sentences:
if word in line:
if count < 10: print(line) # <--------
count = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485511.html
標籤:Python python-3.x
上一篇:python中的多次調度
