繁体   English   中英

如何从txt文件中提取不同行的两个单词之间的单词?

[英]How to extract words between two words of different line from a txt file?

我有一个.txt文件,其中包含几行,我想从每一行中提取特定的单词

例:
txt文件包含

A部分: 12 10 * 2 = 20
B部分: 6 4 * 5 = 20
C部分: 5 3 * 10 = 30

我想将12提取为变量,将6和5提取为不同的变量
(冒号后的第一个数字或冒号后的两个空格之间的数字))

只需阅读文本,拆分,提取并存储在这样的数组中即可!

file=open("filename.txt","r+")    
fileText=file.read()
file.close()
linesArr=fileText.split('\n')
x=linesArr[0].split(': ')[1].split(' ')[0]
y=linesArr[1].split(': ')[1].split(' ')[0]
z=linesArr[2].split(': ')[1].split(' ')[0]
print(x)
print(y)
print(z)

您还可以使用正则表达式从每行中选择第一个数字(在冒号和空格之后):

import re
with open("filename.txt") as file:   
    fileText = file.read()
x, y, z = [int(n) for n in re.findall(": (\d+)", fileText)]
print(x)
print(y)
print(z)

您可以遍历文件的每一行,然后按空格splitsplit ),然后获取第三个元素( third element <=> index = 2 ),它是您想要的数字:

numbers = []

with open('file.txt', 'r') as f:
  for line in f:
    numbers.append(int(line.split()[2]))

print(numbers) # ==> [12, 6, 5]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM