[英]How to find specific strings in a file?
这是我编写的一个脚本,用于查找其中包含 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 '
:
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
这是一个单行:
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.