簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM