Py学习  »  Python

Python——从列表中获取最大年龄。文件

Jun Jie Ong • 3 年前 • 1173 次点击  

你知道我该如何从文本文件中获取最大年龄并打印出来吗?

文本文件:

Name, Address, Age,Hobby
Abu, “18, Jalan Satu, Penang”, 18, “Badminton, Swimming”
Choo,  “Vista Gambier, 10-3A-88, Changkat Bukit Gambier Dua, 11700, Penang”, 17, Dancing
Mutu, Kolej Abdul Rahman, 20, “Shopping, Investing, Youtube-ing”

这是我的代码:

with open("iv.txt",encoding="utf8") as file:
data = file.read()
splitdata = data.split('\n')

我不能从中得到我想要的。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130703
 
1173 次点击  
文章 [ 3 ]  |  最新文章 3 年前
jasonmzx
Reply   •   1 楼
jasonmzx    3 年前

你所做的一切

with open("iv.txt",encoding="utf8") as file:
data = file.read()
splitdata = data.split('\n')

正在创建要分析的数据结构。。 现在你有了所有字符串的列表 splitdata

你可以拆分空间,获取第三个元素数组[2]

比较所有这些

Ralph Macêdo
Reply   •   2 楼
Ralph Macêdo    3 年前

我相信有一个内置功能可以解析像您发布的那样的复合字符串,但我不知道,我已经创建了一个CustomParse类来完成这项工作:

class CustomParser():
    def __init__(self, line: str, delimiter: str):
        self.line = line
        self.delimiter = delimiter

    def split(self):
        word = ''
        words = []
        inside_string = False

        for letter in line:
            if letter in '“”"':
                inside_string = not inside_string
                continue
            if letter == self.delimiter and not inside_string:
                words.append(word.strip())
                word = ''
                continue
            word += letter
        words.append(word.strip())

        return words


with open('people_data.csv') as file:
    ages = []
    for line in file:
        ages.append(CustomParser(line, ',').split()[2])
    print(max(ages[1:]))

希望有帮助。

oda
Reply   •   3 楼
oda    3 年前

这管用!我希望有帮助。如果有任何问题,请告诉我(我必须很快完成这项工作,因为我很忙,但我今天晚些时候会回来改进这项工作,并添加额外的解释)。

这种方法基本上假定 Hobby 里面没有数字。

import csv

max_age = 0
with open("iv.txt", encoding = "utf8") as f:
    spamreader = csv.reader(f, delimiter=',')
    # skip first row
    next(spamreader)
    for row in spamreader:
        for i in reversed(row):
            try:
                i = int(i)
                break
            except ValueError:
                pass
        print(i)
        if i > max_age:
            max_age = i

print(f"\nMax age from file: {max_age}")

输出:

18
17
20

Max age from file: 20