[英]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.