我有以下任務。我必須在我的 file.txt 中找到一個特定的模式(單詞)(是一首以頁面為中心的歌曲),并列印出行號 其中包含模式的行,以消除左邊的空格。你可以在這里看到正確的輸出:
92 Meant in croaking "Nevermore."
99 She shall press, ah, nevermore!
107 Quoth the Raven, "Nevermore."
115 Quoth the Raven, "Nevermore."
and without this: my_str = ' ' str(count) ' ' line.lstrip(), it will print:
92 Meant in croaking "Nevermore."
99 She shall press, ah, nevermore!
107 Quoth the Raven, "Nevermore."
115 Quoth the Raven, "Nevermore."
This is my code, but i want to have only 4 lines of code
```python
def find_in_file(pattern,filename):
my_str = ''
with open(filename, 'r') as file:
for count,line in enumerate(file):
if pattern in line.lower():
if count >= 10 and count <= 99:
my_str = ' ' str(count) ' ' line.lstrip()
else:
my_str = str(count) ' ' line.lstrip()
print(my_str)
uj5u.com熱心網友回復:
其實一行就可以完成:
''.join(f' {count} {line.lstrip()}' if 10 <= count <= 99 else f'{count} {line.lstrip()}' for count, line in enumerate(file) if pattern in line.lower())
然而,這似乎有點太長了......
根據評論區,可以簡化為:
''.join(f'{count:3} {line.lstrip()}' for count, line in enumerate(file) if pattern in line.lower())
uj5u.com熱心網友回復:
def find_in_file(pattern,filename):
with open(filename, 'r') as file:
# 0 based line numbering, for 1 based use enumerate(file,1)
for count,line in enumerate(file):
if pattern in line.lower():
print(f"{count:>3} {line.strip()}")
將是 4 行代碼(在函式內部)并且應該與您得到的相同。
也可以在一行中:
def find_in_file(pattern,filename):
# 1 based line numbering
return '\n'.join(f'{count:>3} {line.strip()}' for count, line in enumerate(file,1) if pattern in line.lower())
請參閱pythons 迷你格式語言。
uj5u.com熱心網友回復:
您可以使用格式化字串來確保數字始終使用三個字符,即使它們只有 1 位或 2 位數字。
我也更喜歡使用str.strip而不是str.lstrip, 來擺脫尾隨空格;特別是,從檔案中讀取的行通常會以換行符結尾,然后print會添加第二個換行符,如果我們不洗掉它們,我們最終會出現太多的換行符。
def find_in_file(pattern,filename):
with open(filename, 'r') as file:
for count,line in enumerate(file):
if pattern in line.lower():
print('{:3d} {}'.format(count, line.strip()))
find_in_file('nevermore','theraven.txt')
# 55 Quoth the Raven "Nevermore."
# 62 With such name as "Nevermore."
# 69 Then the bird said "Nevermore."
# 76 Of 'Never—nevermore'."
# 83 Meant in croaking "Nevermore."
# 90 She shall press, ah, nevermore!
# 97 Quoth the Raven "Nevermore."
# 104 Quoth the Raven "Nevermore."
# 111 Quoth the Raven "Nevermore."
# 118 Quoth the Raven "Nevermore."
# 125 Shall be lifted—nevermore!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/467621.html
