简体   繁体   中英

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

I have a .txt file which contains few lines and I wanted to extract specific words from each line

Example:
the txt file contains

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

I wanted to extract 12 into a variable similarly 6 and 5 to different variables
(the 1st digits after the colon or the digits between two spaces after the colon) )

Just read the text, split, extract and store in an array like this!

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)

You could also use a regular expression to pick the first number from each line (after the colon and space):

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)

You could loop through each line of the file and split it by space ( ), and get the third element ( third element <=> index = 2 ), which is the number you want:

numbers = []

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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