标题: [问题求助] [己解决]Python如何读取文本数? [打印本页]
作者: keshun 时间: 2020-12-30 22:17 标题: [己解决]Python如何读取文本数?
本帖最后由 keshun 于 2020-12-31 18:15 编辑
1.txt内容:
A:XRP B:-36.15% C:0.1866 D:-32.39% E:-59.08% F:0.41% G:-33.01%- with open("1.txt", "r") as f:
- msg = f.readlines()[0]
- print(msg)
复制代码
请教!代码读取1.txt显示'C','F'两组数。
print(C) #显示0.1866
print(F) #显示0.41%
作者: ivor 时间: 2020-12-31 08:24
- with open("1.txt", "r") as f:
- msg = f.readlines()[0].split()
- my_d = {}
- for i in msg:
- my_d[i.split(':')[0]]=i.split(':')[1]
- print(my_d['C'])
- print(my_d['F'])
复制代码
作者: netdzb 时间: 2020-12-31 09:14
本帖最后由 netdzb 于 2020-12-31 09:16 编辑
回复 2# ivor
代码通不过啊
msg = '''A:XRP B:-36.15% C:0.1866 D:-32.39% E:-59.08% F:0.41% G:-33.01%'''
my_d = {}
for i in msg:
my_d[i.split(':')[0]]=i.split(':')[1]
print(my_d['C'])
print(my_d['F'])
======
my_d[i.split(':')[0]]=i.split(':')[1]这行报错了。
作者: Gin_Q 时间: 2020-12-31 09:17
本帖最后由 Gin_Q 于 2020-12-31 10:21 编辑
回复 1# keshun
你的文本格式是否如你所说,是否统一一致- >>> a
-
- 'A:XRP B:-36.15% C:0.1866 D:-32.39% E:-59.08% F:0.41% G:-33.01%'
- >>> b=a.split()
-
- >>> b[2].split(':')
-
- ['C', '0.1866']
- >>> b[5].split(':')
-
- ['F', '0.41%']
复制代码
- >>> a
- 'A:XRP B:-36.15% C:0.1866 D:-32.39% E:-59.08% F:0.41% G:-33.01%'
- >>> d=re.compile('[CF]:(\d+.?\d+%?)')
- >>> d.findall(a)
- ['0.1866', '0.41%']
复制代码
欢迎光临 批处理之家 (http://www.bathome.net/) |
Powered by Discuz! 7.2 |