温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python 3.x - I want to find the highest number using import re .txt
import python-3.x text-files

python 3.x - 我想使用import re .txt查找最高编号

发布于 2020-03-27 11:38:10

我希望能够使用该re模块在文本文件中搜索所有数字并找到最大数字我需要在哪里编辑代码以实现此目标?该random.txt看起来财产以后这样的: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)

该文件只运行了一次,给了我答案0

查看更多

查看更多

提问者
Erik K.
被浏览
26
shaik moeed 2019-07-03 23:22

尝试这个,

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))

输出:

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']