Warm tip: This article is reproduced from stackoverflow.com, please click
import python-3.x text-files

I want to find the highest number using import re .txt

发布于 2020-03-27 10:26:28

I want to be able to just search for all digits in a text file and find the max number, using the re module. Where do I need to edit my code to accomplish this goal? The random.txt looks somthing like the following: Datq15UxkNwMN5zUQhd46J8WeF9RjAq214TlJiQ8EkZvmdOpmBOdd365mICKC67GGvqwbLqV2Gox3n3E5WC1Vq8C22lZ6sL3Ip24untQyw46g2219WlA07GP30PNvc8o3hCb2d283l68mh86RH6gDNbN7kIXmdO4a84hUz73905o3BlR71YCQF985JTz54FRoN32pM8N23YcYd7jv9Ys575UzaH9RZ7sosMdeqnTgnVt0bH99b2P5ilvJ33QaJ6G76VU8vPN

import re
with open('content.txt', 'r',) as f:
    contents = f.read()

    number = 0
    pattern = re.compile(r'\d')
    matches = pattern.finditer('content.txt')
    for match in matches:
        n = int(match)
        if saved <= n:
            number = int(match)
    print(number)

the file just ran once and gave me the answer 0

Questioner
Erik K.
Viewed
24
shaik moeed 2019-07-03 23:22

Try this,

import re
with open('file1.txt', 'r') as f:
    data = f.read()
    list_of_numbers = re.findall(r'(?:[\d]+)',data)
    list_of_numbers = map(int, list_of_numbers)

print(max(list_of_numbers))

Output:

73905 # max number

your list_of_numbers look like this
['15', '5', '46', '8', '9', '214', '8', '365', '67', '2', '3', '3', '5', '1', 
'8', '22', '6', '3', '24', '46', '2219', '07', '30', '8', '3', '2', '283', '68', 
'86', '6', '7', '4', '84', '73905', '3', '71', '985', '54', '32', '8', '23', '7', 
'9', '575', '9', '7', '0', '99', '2', '5', '33', '6', '76', '8']