首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python -在文件中查找最多4行代码中的模式

Python -在文件中查找最多4行代码中的模式
EN

Stack Overflow用户
提问于 2022-04-29 09:16:10
回答 3查看 52关注 0票数 0

我有以下任务。我必须在我的file.txt中找到一个特定的模式(Word)(这是一首以页面为中心的歌曲),并打印出行号+其中有模式的行,去掉左边的空格。您可以在这里看到正确的输出:

代码语言:javascript
复制
 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(模式,文件名):

代码语言:javascript
复制
my_str = ''
代码语言:javascript
复制
with open(filename, 'r') as file:
代码语言:javascript
复制
    for count,line in enumerate(file):
代码语言:javascript
复制
        if pattern in line.lower():
代码语言:javascript
复制
            if count >= 10 and count <= 99:
代码语言:javascript
复制
                my_str += ' '+str(count)+ ' ' + line.lstrip()
代码语言:javascript
复制
            else:
代码语言:javascript
复制
                my_str += str(count)+ ' ' + line.lstrip()
代码语言:javascript
复制
print(my_str)
代码语言:javascript
复制
EN

回答 3

Stack Overflow用户

发布于 2022-04-29 09:22:18

实际上,可以完成一行:

代码语言:javascript
复制
''.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())

不过,这似乎有点太长了..。

根据评论区,可以简化:

代码语言:javascript
复制
''.join(f'{count:3} {line.lstrip()}' for count, line in enumerate(file) if pattern in line.lower())
票数 1
EN

Stack Overflow用户

发布于 2022-04-29 09:26:22

代码语言:javascript
复制
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行代码(在函数中),并且应该与您得到的代码相等。

也有可能在一行:

代码语言:javascript
复制
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())

蟒蛇迷你格式语言

票数 0
EN

Stack Overflow用户

发布于 2022-04-29 09:31:58

您可以使用格式化字符串来确保数字始终使用三个字符,即使它们只有1或2个数字。

我也更喜欢使用str.strip而不是str.lstrip,以消除尾随空格;特别是,从文件中读取的行通常以换行结束,然后print将添加第二个换行符,如果不去掉它们,我们将得到太多的换行符。

代码语言:javascript
复制
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!
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72055615

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档