返回列表 发帖

[问题求助] 求助Python字符串分割

文件中的字符串格式相同,node:9000006 id:0x0001 proxy:0x0000 info:0x40
要求把每行:后的字符串提取出来,变成9000006 0x0001 0x0000 0x40存储在变量中。
import os
file_path = os.path.abspath(r'C:\Users\14232\Downloads\topo.txt')
#打开文件
print("文件路径:",file_path)
with open(file_path,'r') as file:
    content = file.read()
    print("文件内容")
    print(content)
    values = []
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            # 去掉行末的换行符并以 ':' 分割
            parts = line.strip().split(':')
            if len(parts) > 1:
                # 将 ':' 后面的部分储存到变量中
                value = parts[1].strip()  # 去掉可能的空格
                values.append(value)
                for value in values:
                    print(value)COPY
该如何写

啊,除了重复print外,这代码不行么?

TOP

回复 2# Five66


    不行,代码输出的是9000006 id,和我要的效果不一样

TOP

回复 2# Five66


    大佬能教教我在,怎么写吗

TOP

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

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

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

TOP

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

回复 4# 占卜家


    啊,原来不是一行一个的?试试再用空格split一下吧

TOP

回复 5# aloha20200628


    感谢大佬,已解决

TOP

返回列表