簡體   English   中英

使用正則表達式搜索 Python 文件

[英]Python file search using regex

我有一個有很多行的文件。 每行以 {"id": 開頭,后跟引號中的 ID 號。 (即{“id”:“106”)。 我正在嘗試使用正則表達式逐行搜索整個文檔並打印匹配 5 個不同 id 值的行。 為此,我創建了一個帶有 id 的列表,並且只想遍歷列表中以 {"id": "(id number from list)" 開頭的匹配行。 我真的很困惑如何做到這一點。 這是我到目前為止所擁有的:

f= "bdata.txt"    
statids = ["85", "106", "140", "172" , "337"] 
x= re.findall('{"id":', statids, 'f')
for line in open(file):
            print(x)

我不斷收到的錯誤代碼是:TypeError: 不支持的操作數類型 &: 'str' 和 'int'

我需要整行進行匹配,以便我可以將其拆分並將其放入一個類中。

有什么建議嗎? 謝謝你的時間。

您可以使用正則表達式^\\{\\"id\\": \\"(\\d+)\\"從行中檢索 id,其中 group#1 的值將為您提供 id。 然后,您可以檢查statids是否存在該 id。

演示:

import re

statids = ["85", "106", "140", "172", "337"]

with open("bdata.txt") as file:
    for line in file:
        search = re.search('^\{\"id\": \"(\d+)\"', line)
        if search:
            id = search.group(1)
            if id in statids:
                print(line.rstrip())

對於文件中的以下示例內容:

{"id": "100" hello
{"id": "106" world
{"id": "2" hi
{"id": "85" bye
{"id": "10" ok
{"id": "140" good
{"id": "165" fine
{"id": "172" great
{"id": "337" morning
{"id": "16" evening

輸出將是:

{"id": "106" world
{"id": "85" bye
{"id": "140" good
{"id": "172" great
{"id": "337" morning

我這里的問題是您使用 re.findall 的方式,根據文檔,您必須將正則表達式作為第一個參數傳遞,並將要與表達式匹配的字符串作為第二個參數傳遞。 在您的情況下,我認為您應該這樣做:

pattern = f'id: ({"|".join(statsids)})'
with open(f) as file:
  for line in file:
      match = re.findall(pattern, line)
      print(match.group(0))

在正則表達式中管道運算符“|” 通過將所有 id 作為字符串加入 | 在它們之間將找到它匹配一個或另一個 ID 的所有情況。 match.group 行返回找到它的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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