简体   繁体   English

如何在文件中查找特定字符串?

[英]How to find specific strings in a file?

This is a script that I have written to find all the lines with usb in it.这是我编写的一个脚本,用于查找其中包含 usb 的所有行。 However, the problem is that if also returns lines if they have words such as usbcore as well.但是,问题在于如果它们也有诸如 usbcore 之类的单词,if 也会返回行。 I am interested in lines that contain only the words usb.我对仅包含单词 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!')

You can try to find the word ' usb ' with spaces:您可以尝试使用空格找到单词' 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!')
  • Example:例子:

     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

Here`sa one-liner:这是一个单行:

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

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

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