【问题标题】:How to find specific strings in a file?如何在文件中查找特定字符串?
【发布时间】:2020-06-01 18:29:31
【问题描述】:

这是我编写的一个脚本,用于查找其中包含 USB 的所有行。但是,问题在于如果它们也有诸如 usbcore 之类的单词,if 也会返回行。我对只包含 usb 字样的行感兴趣。

#!/usr/bin/python

import sys

logFile = open(sys.argv[1])

print("Printing all lines with USB in it...")

for line in logFile.readlines():
    if line.lower().find('usb') != -1:
        print(line)

print('Done!')

【问题讨论】:

  • 根据您的具体标准,搜索例如'usb' 代替。
  • 您应该按照here 的说明使用正则表达式。
  • ctenar 如果单词在句首并且前面没有空格怎么办?在我看来,正则表达式会是一种更好的方法
  • 您可以对条件if re.search(r'\busb\b', line, re.I): print(line) 使用正则表达式。这发现usb,不区分大小写。 \b 表示必须被行首、空格或行尾等边框包围。
  • 你可以查看我的答案,它会为你工作

标签: python


【解决方案1】:

您可以尝试查找带有空格的单词' usb '

import sys

logFile = open(sys.argv[1])

print("Printing all lines with USB in it...")

for line in logFile.readlines():
    if line.lower().find(' usb ') != -1:
        print(line)

print('Done!')
  • 例子:

    a = ' i have usbbox '
    b = ' i have usb '
    a.find('usb') # != -1
    a.find(' usb ') # = -1 , bcs it doesnt contain the word 'usb' only
    b.find(' usb ') # != -1 , it contains it
    

【讨论】:

    【解决方案2】:

    这是一个单行:

    with open(sys.arg[1]) as f: 
        print(''.join([l for l in f.readlines() if ' ubs ' in l.lower()])
    

    【讨论】:

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