慕尼黑8549860
2022-08-11 17:45:25
我對python非常陌生,我需要使用正則表達式。我在一個目錄中有多個.txt文件需要解析。這些.txt文件中的每一個都有多次出現的單詞“指令”。我需要抓取“指令”一詞后面的數字,并將其添加到將在excel中顯示的列表中。這是以這樣的方式完成的,我有一列“指令”,其中包含所有指令編號,并且我有一行所有.txt文件名。我最終需要在指令編號前面加上一個“是”或“否”,如果它存在于特定的.txt文件中。我想知道如何獲取“指令”一詞后面的數字并將其添加到列表中(也許)。稍后使用此列表來制定Excel文件。編寫此正則表達式指令的方法是什么?這是我到目前為止的代碼import csv import re import glob import os inst_num = []os.chdir (r"C:\Users\10002\Desktop\work\scripts")for file in glob.glob("*.txt"): with open (file, 'r') as f: for line in f: inst = re.compile ('instruction:(\d+)',line) if inst.search(line) is not None: inst_num = inst.search(line).group(1)
1 回答

慕容森
TA貢獻1853條經驗 獲得超18個贊
首先,不要將要搜索的文本字符串作為第二個參數(可選的第二個參數是要使用的標志,例如)。其次,應該將 to 的調用從循環中取出,否則您將破壞預編譯正則表達式的目的。第三,你問了多個問題,這通常是不受歡迎的。我將向您展示如何創建數字列表。如果您對如何從中創建CSV文件有單獨的問題,請發布單獨的問題。compilere.IGNORECASEcompile
import csv
import re
import glob
import os
inst_num = []
inst = re.compile('instruction:(\d+)') # compiled regex
os.chdir (r"C:\Users\10002\Desktop\work\scripts")
for file in glob.glob("*.txt"):
with open (file, 'r') as f:
for line in f:
match = inst.search(line) # do the search once
if match:
inst_num.append(match.group(1)) # add to list
添加回答
舉報
0/150
提交
取消