我想使用import re .txt查找最高编号

时间:2019-07-03 14:58:35

标签: python-3.x import text-files

我希望能够使用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

2 个答案:

答案 0 :(得分:0)

您正在寻找“ content.txt”字符串中的匹配项,因此没有匹配项。另外MatchObject不能转换为int:

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

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

答案 1 :(得分:0)

尝试一下

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