Board logo

标题: [问题求助] 求助Python字符串分割 [打印本页]

作者: 占卜家    时间: 2024-8-26 12:04     标题: 求助Python字符串分割

文件中的字符串格式相同,node:9000006 id:0x0001 proxy:0x0000 info:0x40
要求把每行:后的字符串提取出来,变成9000006 0x0001 0x0000 0x40存储在变量中。
  1. import os
  2. file_path = os.path.abspath(r'C:\Users\14232\Downloads\topo.txt')
  3. #打开文件
  4. print("文件路径:",file_path)
  5. with open(file_path,'r') as file:
  6.     content = file.read()
  7.     print("文件内容")
  8.     print(content)
  9.     values = []
  10.     with open(file_path, 'r', encoding='utf-8') as file:
  11.         for line in file:
  12.             # 去掉行末的换行符并以 ':' 分割
  13.             parts = line.strip().split(':')
  14.             if len(parts) > 1:
  15.                 # 将 ':' 后面的部分储存到变量中
  16.                 value = parts[1].strip()  # 去掉可能的空格
  17.                 values.append(value)
  18.                 for value in values:
  19.                     print(value)
复制代码
该如何写
作者: Five66    时间: 2024-8-26 13:00

啊,除了重复print外,这代码不行么?
作者: 占卜家    时间: 2024-8-26 13:37

回复 2# Five66


    不行,代码输出的是9000006 id,和我要的效果不一样
作者: 占卜家    时间: 2024-8-26 13:37

回复 2# Five66


    大佬能教教我在,怎么写吗
作者: aloha20200628    时间: 2024-8-26 13:43

本帖最后由 aloha20200628 于 2024-8-26 14:10 编辑

回复 1# 占卜家
  1. import re
  2. for line in open(r'C:\Users\14232\Downloads\topo.txt', 'r', -1):   
  3. if line:=line.strip():
  4. nl = re.split(':| ', line, re.M)
  5. print(' '.join(nl[1::2]))
复制代码

python 3.8+开始支持海象运算符 :=
若是较低版本可用以下代码
  1. import re
  2. for line in open(r'C:\Users\14232\Downloads\topo.txt', 'r', -1):   
  3. line = line.strip()
  4. if line:
  5. nl = re.split(':| ', line, re.M)
  6. print(' '.join(nl[1::2]))
复制代码

作者: Five66    时间: 2024-8-26 13:45

本帖最后由 Five66 于 2024-8-26 13:47 编辑

回复 4# 占卜家


    啊,原来不是一行一个的?试试再用空格split一下吧
作者: 占卜家    时间: 2024-8-26 14:35

回复 5# aloha20200628


    感谢大佬,已解决




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2