繁体   English   中英

Python从文件中搜索字符串值

[英]Python search string value from file

我正在尝试创建一个python脚本来查找txt文件中的特定字符串。例如,我的文本文件dbname.txt包含以下内容:

Level1="50,90,40,60"
Level2="20,10,30,80"

我将需要脚本来搜索文件中的用户输入并打印等于该值的输出,例如:

Please enter the quantity : 50
The level is : Level1

我卡在文件的搜索部分中了吗? 有什么建议吗?

提前致谢

在这种有限的情况下,我建议使用正则表达式。

import re
import os

您需要一个文件来获取信息,为它创建一个目录(如果不存在),然后编写该文件:

os.mkdir = '/tmp' 
filepath = '/tmp/foo.txt'
with open(filepath, 'w') as file:
    file.write('Level1="50,90,40,60"\n'
               'Level2="20,10,30,80"')

然后阅读信息并进行解析:

with open(filepath) as file:
    txt = file.read()

我们将使用带有两个捕获组的正则表达式,第一个捕获组,Level,第二个捕获数字:

mapping = re.findall(r'(Level\d+)="(.*)"', txt)

这将给我们一个元组对的列表。 从语义上讲,我会考虑它们的键和值。 然后获取用户输入并搜索数据:

user_input = raw_input('Please enter the quantity: ')

我输入50,然后:

for key, value in mapping:
    if user_input in value:
        print('The level is {0}'.format(key))

打印:

The level is Level1

使用mmap模块,这是最有效的方法。 mmap不会将整个文件读入内存(它会按需分页),并且同时支持find()和rfind()

with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    position = mm.find('blah')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM