R
R
Rostislav Ivanov2021-11-16 13:09:47
Python
Rostislav Ivanov, 2021-11-16 13:09:47

How to find the number after a specific word in a word document using Python?

Good afternoon.

There is a text document. It contains some text and numbers.
For example:

Hello Hello Hello
639 Number: 639
Hello 275 639/275 Hello Hello Number: 275
Hello 275 Hello 639 Hello
275 Hello

As you can see, there are lines that contain the text "Number: 639" and "Number: 275" ,
after which there is nothing.
I need to search for the text "Number:", and somehow write the numbers 639 and 275 into 2 different variables. For example: x, y.

I gave an example with random numbers, they may be different.
I mean that after the text "Number: " there may be other random numbers, and I need to write them to the variables x, y.

I also wrote a code that displays the entire line if there is a text "Number: ".

word = "Число:  "
f = open(r"C:\Test1.txt","r")
for line in f:
    if word in line:
        print(line, end="")
f.close()

It gives me this:
639 Число: 639
Привет 275 639/275 Привет Привет Число: 275
Привет Число: 275

A Python program reads a text document from top to bottom.
That's why I also wanted to ask. Is it possible to make the text "Number:" searched from bottom to top. Those. the value 275 was entered into the variable x, or another number that will be after the text "Number: "?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question