我有以下任务。我必须在我的file.txt中找到一个特定的模式(Word)(这是一首以页面为中心的歌曲),并打印出行号+其中有模式的行,去掉左边的空格。您可以在这里看到正确的输出:
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
```pythondef find_in_file(模式,文件名):
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)发布于 2022-04-29 09:22:18
实际上,可以完成一行:
''.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())发布于 2022-04-29 09:26:22
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())见蟒蛇迷你格式语言。
发布于 2022-04-29 09:31:58
您可以使用格式化字符串来确保数字始终使用三个字符,即使它们只有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://stackoverflow.com/questions/72055615
复制相似问题