【发布时间】:2023-02-01 22:35:41
【问题描述】:
我创建了这段代码,让用户指向一个目录,并通过该目录查找 .xml 文件。一旦找到,程序应该搜索每个文件以查找长度为 32 位的字符串。这是唯一的要求,此时内容并不重要,只要它返回 32 位字符串即可。
当运行程序迭代可用文件时,我尝试使用 Python 中的 regex 模块,如下所示。返回所有文件名,但 String_recovery 函数仅返回空列表。我已经确认 xml 在视觉上包含 32 位字符串。
import os
import re
import tkinter as tk
from tkinter import filedialog
def string_recovery(data):
short_string = re.compile(r"^[a-zA-Z0-9\-._]{32}$")
strings = re.findall(short_string, data)
print(strings)
def xml_search(directory):
xml_files = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".xml"):
xml_files.append(os.path.join(root, file))
print("The following XML files have been found.")
print(xml_files)
for xml_file in xml_files:
with open(xml_file, "r") as f:
string_recovery(f.read())
def key_finder():
directory = filedialog.askdirectory()
xml_search(directory)
key_finder()
【问题讨论】:
-
您的“32 位字符串”是什么样的?您的 XML 文件是什么样的?
-
欢迎来到堆栈溢出。我无法理解这个问题,因为字符串的长度没有测量位。此外,该函数根本没有
return(请阅读What is the purpose of the return statement? How is it different from printing?),并且唯一涉及的列表是xml_files。 -
m标志是默认标志吗?我不认为在这种情况下^和$是文件的开头和结尾而不是一行。也许尝试将m标志添加到您的parrern。
标签: python python-3.x