[英]Find specific value from text file using python
我正在学习python,我不知道如何从文本文件中获取特定值。
这是文本文件的示例。
a1: 1 a2: 2 a3: 3 a4: 4
a5: 5 a6: 6 a7: 7 a8: 8
我试图在不同的文本文件中打印出值 (1 2 3 4 5 6 7 8)。
# Import regex library
import re
# Open the file and read the text
with open('file1.txt') as file:
text = file.read()
# Get list of integers in the file. \d matches digits in regex.
numbers = re.findall('a\d:\s*(\d)', text)
# Create a second file and write the numbers to it
with open('file2.txt', 'w') as file:
file.write(' '.join(numbers))
尝试这个:
file = open('samp.txt')
file = file.readlines()
numbers_array = []
for line in lines:
parts = line.strip('\n').split(' ')
numbers = [i for i in parts if i.isnumeric()]
numbers_array.extend(numbers)
with open('out.txt','a') as out:
out.write(' '.join(numbers_array))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.