文本fi中的python搜索

2024-09-27 09:34:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在txt文件中搜索变量“elementid”

  f = open("wawi.txt", "r")
  r = f.read()
  f.close()
  for line in r:
      if elementid in line:
          print("elementid exists")
          break

元素ID可能是123456

txt包含三行:

^{pr2}$

但是代码没有打印“elementid exists”,为什么? 我使用python3.4


Tags: 文件intxt元素forclosereadif
3条回答

将整数转换为字符串,然后迭代文件中的行,检查当前行是否与elementid匹配。在

elementid = 123456 # given
searchTerm = str(elementid)
with open('wawi.txt', 'r') as f:
    for index, line in enumerate(f, start=1):
        if searchTerm in line:
            print('elementid exists on line #{}'.format(index))

输出

^{pr2}$

另一种方法

一个更可靠的解决方案是从每一行中提取所有的数字,并在所述数字中找到数字。如果当前行中的任何位置都存在该数字,则将声明匹配。在

方法

numbers = re.findall(r'\d+', line)   # extract all numbers
numbers = [int(x) for x in numbers]  # map the numbers to int
found   = elementid in numbers       # check if exists

示例

^{4}$

当您read文件时,您将整个内容读入一个字符串。在

当你迭代它时,你一次只得到一个字符。在

尝试打印线条:

for line in r:
     print line

你会得到

^{pr2}$

你需要说:

for line in r.split('\n'):
    ...

只是重新排列你的代码

f = open("wawi.txt", "r")
for line in f:
    if elementid in line: #put str(elementid) if your input is of type `int`
        print("elementid exists")
        break

相关问题 更多 >

    热门问题