【问题标题】:find line index in a text file python在文本文件python中查找行索引
【发布时间】:2018-03-28 16:11:05
【问题描述】:

我想在文本文件(内容)中获取与某个字符串(在本例中为 InChI=1S/C11etc..)对应的行的索引,这是我的代码:

with open('compounds.dat', encoding='utf-8', errors='ignore') as f:
    content = f.readlines()
    index = [x for x in range(len(content)) if "InChI=1S/C11H8O3/c1-6-5-9(13)10-7(11(6)14)3-2-4-8(10)12/h2-5" in content[x].lower()]
    print(index)

但是我得到空括号 []。但我很确定这条线存在,因为如果我运行这个:

for line in f:
    if u"InChI=1S/C11H8O3/c1-6-5-9(13)10-7(11(6)14)3-2-4-8(10)12/h2-5" in line:
        l = line

我得到了我感兴趣的线路。

【问题讨论】:

  • 您的模式包含大写字符,而您在比较之前将字符串 content[x].lower() 小写...为什么?
  • 使用正则表达式..如果文件不是太大,Python 正则表达式的性能还不错。

标签: python search indexing line


【解决方案1】:

扩展我的评论,调用lower() 将小写您的目标字符串,而您的搜索字符串有大写字母 - 您不可能匹配这样的内容。

此外,您不必遍历范围。 for 可以直接遍历content 中的项目。这将起作用。

search_str = "InChI=1S/C11H8O3/c1-6-5-9(13)10-7(11(6)14)3-2-4-8(10)12/h2-5"
lines = [x for x in content if search_str in content]

【讨论】:

    【解决方案2】:

    不要在代码中使用.lower(),它应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      相关资源
      最近更新 更多