【问题标题】:python search in text filepython在文本文件中搜索
【发布时间】:2015-03-24 11:37:24
【问题描述】:

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

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

elementid 可能是 123456

txt 包含三行:

1235
56875
123456

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

【问题讨论】:

  • 改为:for line in f:
  • 抱歉,误诊。见答案。
  • @mshsayem:更好的是:with open('wawi.txt', 'r') as f: for line in f: print(line)this answer
  • 如果不需要python,你也可以尝试使用grep

标签: python file search


【解决方案1】:

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

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

尝试打印线条:

for line in r:
     print line

你会得到

1
2
3
5

5
6
8
7
5

1
2
3
4
5
6

你需要说:

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

【讨论】:

    【解决方案2】:

    只是重新排列你的代码

    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
    

    【讨论】:

    • 它有效,但他说 258311 与 25831 相同。所以我尝试使用 elementid == 行,但这不起作用
    【解决方案3】:

    将整数转换为字符串 THEN 遍历文件中的行,检查当前行是否与 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))
    

    输出

    elementid exists on line #3
    

    另一种方法

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

    方法

    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
    

    示例

    import re
    elementid = 123456 # given
    with open('wawi.txt', 'r') as f:
        for index, line in enumerate(f, start=1):
            if elementid in [int(x) for x in re.findall(r'\d+', line)]:
                print('elementid exists on line #{}'.format(index))
    

    【讨论】:

      【解决方案4】:
      f = open("wawi.txt", "r")
      
      for lines in f:
          if "elementid" in lines:
              print "Elementid found!"
          else:
              print "No results!"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多