[英]extracting certain strings from a a file using python
我有幾行文件。 在這些行中,我將僅選擇以xxx
開頭的行。 現在以xxx
開頭的行具有如下模式:
xxx:(12:"pqrs",223,"rst",-90)
xxx:(23:"abc",111,"def",-80)
我只想提取第一個雙引號中的字符串,即“ pqrs”和“ abc”。
感謝使用正則表達式的任何幫助。
我的代碼如下:
with open("log.txt","r") as f:
f = f.readlines()
for line in f:
line=line.rstrip()
for phrase in 'xxx:':
if re.match('^xxx:',line):
c=line
break
這段代碼給我錯誤
您的代碼已縮進。 您的f = f.readlines()
前面有9個空格,而for line in f:
有4個空格。 它應如下所示。
import re
list_of_prefixes = ["xxx","aaa"]
resulting_list = []
with open("raw.txt","r") as f:
f = f.readlines()
for line in f:
line=line.rstrip()
for phrase in list_of_prefixes:
if re.match(phrase + ':\(\d+:\"(\w+)',line) != None:
resulting_list.append(re.findall(phrase +':\(\d+:\"(\w+)',line)[0])
results = []
with open("log.txt","r") as f:
f = f.readlines()
for line in f:
if line.startswith("xxx"):
line = line.split(":") # line[1] will be what is after :
result = line[1].split(",")[0][1:-1] # will be pqrs
results.append(result)
您要查找以xxx開頭的行,然后在:上分割行。 :之后的第一件事就是您想要的-直到逗號為止。 然后,您的結果是該字符串,但請刪除引號。 不需要正則表達式。 Python字符串函數會很好
好吧,您正朝着正確的方向前進。
如果輸入很簡單,則可以使用正則表達式組。
with open("log.txt","r") as f:
f = f.readlines()
for line in f:
line=line.rstrip()
m = re.match('^xxx:\(\d*:("[^"]*")',line)
if m is not None:
print(m.group(1))
所有的魔力都在正則表達式中。
^ xxx:(\\ d * :(“ [^”] *“)表示
從該行的開頭開始,匹配“ xxx:(<任意數量的數字>:” <<但不包含>”
並且由於序列“ <<除“>”被括在圓括號中,因此可以作為組使用(通過調用m.group(1))。
PS:下次請確保包括您遇到的確切錯誤
要檢查行是否以xxx開頭,請執行
line.startswith('xxx')
要查找第一個雙引號中的文本,請執行以下操作
re.search(r'"(.*?)"', line).group(1)
(因為match.group(1)
是第一個帶括號的子組)
所以代碼將是
with open("file") as f:
for line in f:
if line.startswith('xxx'):
print(re.search(r'"(.*?)"', line).group(1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.