在搜索带有正则表达式的图案时,将其键入INT,避免了元组的不变性
我目前正在处理一个问题,其中我从文件中读取行,并以此为格式:
-rw-r--r-- 1 jttoivon hyad-all 25399 Nov 2 21:25 exception_hierarchy.pdf
预期的输出是关联元组的列表,例如:
(25399, "Nov", 2, 21, 25, "exception_hierarchy.pdf")
我已经以朗格到的匹配来完成此操作,但是我的答案看起来像:
("25399", "Nov", "2", "21", "25", "exception_hierarchy.pdf")
IS :有什么办法可以在正则匹配期间将数字字符串打入INT并绕过元组的不变性?我已经浏览了我的元素列表,只打印出每个元组中的数字字符串,所以我知道我可以访问它们。问题是我试图打字到INT并意识到什么都没有发生。我必须以某种方式复制整个元组列表吗?似乎很低效率。到目前为止,这是我的代码:
import re
def file_listing(filename="src/listing.txt"):
tuple_list = []
with open(filename, "r") as file:
for lines in file:
current_line = file.readline()
found = re.search(r".* \d .* .* (\d+) (\w+) (\d+) (\d+):(\d+) (.*)", current_line)
if found:
found_groups = found.groups()
for item in found_groups:
if item.isdigit():
print(item) # Found the correct items, but...
#item = int(item) # tuples are immutable!! find another way
tuple_list.append(found_groups)
return tuple_list
def main():
print(file_listing())
if __name__ == "__main__":
main()
I'm currently working on a problem where I read lines from files, with lines formatted as such:
-rw-r--r-- 1 jttoivon hyad-all 25399 Nov 2 21:25 exception_hierarchy.pdf
and the expected output is as list of correlating tuples, for example:
(25399, "Nov", 2, 21, 25, "exception_hierarchy.pdf")
I have accomplished this with regex matching, but my answer looks like:
("25399", "Nov", "2", "21", "25", "exception_hierarchy.pdf")
Is there any way to typecast the number strings to int during regex matching and get around the immutability of tuples? I have gone through my list of tuples and printed out only those number strings in each tuple, so I know I can access them. The problem is I tried to typecast to int and realized that nothing happens. Do I have to somehow copy the entire list of tuples? Seems very inefficient. Here is my code so far:
import re
def file_listing(filename="src/listing.txt"):
tuple_list = []
with open(filename, "r") as file:
for lines in file:
current_line = file.readline()
found = re.search(r".* \d .* .* (\d+) (\w+) (\d+) (\d+):(\d+) (.*)", current_line)
if found:
found_groups = found.groups()
for item in found_groups:
if item.isdigit():
print(item) # Found the correct items, but...
#item = int(item) # tuples are immutable!! find another way
tuple_list.append(found_groups)
return tuple_list
def main():
print(file_listing())
if __name__ == "__main__":
main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
元组是一种不变的结构。您必须创建另一个元组,然后将新元组添加到
tuple_list
中。例如:打印:
Tuple is a structure which is unchangeable. You have to create another tuple and add the new one to
tuple_list
. For example:Prints: