【问题标题】:Looking for any matching terms from file从文件中寻找任何匹配的术语
【发布时间】:2022-11-24 17:35:18
【问题描述】:

我有一个文件,其中包含大量国家、年份和预期寿命年龄的列表。我不知道如何确保只允许用户输入实际存在的年份。弄清楚这一点后,我只需要调用那些年份(具有相应的国家名称、代码和预期寿命。我该怎么做?


import pathlib

cwd = pathlib.Path(__file__).parent.resolve()
data_file = f'{cwd}/life-expectancy.csv'

with open(data_file) as f:
    while True:

        user_year = input('Enter the year of interest: ')
        
        for lines in f:
            cat = lines.strip().split(',')
            country = cat[0]
            code = cat[1]
            year = cat[2]
            age = cat[3]
        if any( [year in user_year for year in cat[2]] ):
            print(f'Your year is {user_year}. That is one of our known years.')
            print(year)
            print()
            continue
        else:
            print('Please enter a valid year (1751-2019)')
        
            
        print('test')  

【问题讨论】:

  • 几个 cmet:您在每次用户尝试时都会读取您的文件。为什么不在进入输入部分之前阅读一次?并请添加一个示例,说明用户与脚本的交互方式,例如通过显示控制台在各种情况下应该是什么样子。
  • 您的文件中是否存在从 1751 年到 2019 年的所有日期?
  • “life-expectancy.csv”中的代码和年龄是多少?您能否在此列下提供示例值?

标签: python


【解决方案1】:

解决方案 1

如果从 1751 到 2019 的所有日期都在你的文件中,那么你不需要阅读你的文件来检查,你可以简单地这样做:

# Ask the user for the year
prompt_text = "Enter the year of interest: "
user_year = int(input(prompt_text))
while not 1751 <= user_year <= 2019:
    print("Please enter a valid year (1751-2019)")
    user_year = int(input(prompt_text))

之后,您可以读取文件并仅在年份匹配时存储数据:

# Get the data for the asked year
# Example of final data: [("France", "FR", 45), ("Espagne", "ES", 29)]
data = []
with open(data_file, "r", encoding="utf-8") as file:
    for line in file:
        country, code, year, age = line.strip().split(",")
        if int(year) == user_year:
            data.append((country, code, int(age)))

方案二

如果您确实需要检查文件中的年份,例如因为 1845 不在其中,然后读取文件一次并将所有数据存储在按年份索引的字典中,如果存在则返回所询问年份的数据:

data = {}
with open(data_file, "r", encoding="utf-8") as file:
    for line in file:
        country, code, year, age = line.strip().split(",")
        year = int(year)
        if year in data:
            data[year].append((country, code, int(age)))
        else:
            data[year] = [(country, code, int(age))]

prompt_text = "Enter the year of interest: "
user_year = int(input(prompt_text))
while user_year not in data:
    print("The year is not present in the file")
    user_year = int(input(prompt_text))
print(data[user_year])

【讨论】:

    【解决方案2】:

    一个可以使用数据框处理此类案件。要了解有关数据框的更多信息,请查看Pandas.DataFrame

    从数据框中选择特定的列内容:df[[&lt;col_1&gt;, &lt;col_2&gt;]]

    考虑到获取的数据可能会产生以下结果。

    import pandas as pd
    
    df = pd.read_csv("Life Expectancy Data.csv")
    
    year = int(input("Enter the year of interest: "))
    
    
    df = df[["Country", "Year", "Life expectancy "]]
    
    if year in df["Year"].values:
        print(f'Your year is {year}. That is one of our known years.')
        display(df.loc[df["Year"] == year])
    else:
        print("Please enter a valid year (2000-2015)")
    

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 1970-01-01
      • 2019-02-11
      • 2012-01-25
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多