用冒号分析行中的单词(简单的初学者作业)

2024-05-16 21:51:13 发布

您现在位置:Python中文网/ 问答频道 /正文

使用存储在“travel_plans.txt”中的数据创建一个名为destination的列表。列表的每个元素都应该包含文件中的一行,该行列出一个国家和该国境内的城市

“travel_plans.txt”包含:

This summer I will be travelling.
I will go to...
Italy: Rome
Greece: Athens
England: London, Manchester
France: Paris, Nice, Lyon
Spain: Madrid, Barcelona, Granada
Austria: Vienna
I will probably not even want to come back!
However, I wonder how I will get by with all the different languages.
I only know English!

到目前为止,我已经写了以下内容:

with open("travel_plans.txt","r") as fileref:
    for line in fileref:
        row = line.strip().split()
        if ":" in row[0]:
            destination = row
            print(destination)

有没有更好的方法获得相同的输出


Tags: 文件to数据intxt元素列表with
2条回答

公认的答案很好。我有一些其他的建议,因为你正在学习

首先,您可以考虑稍微多的Python(通常指的是“可读”)方法,它可以包括将此分解为多个函数。

def test_line(line):
    """This function returns `None` for lines we don't care about."""
    if ":" in line:
        return line

上面的第二行称为“docstring”。它向代码的其他读者解释代码的作用(包括提醒未来的您)

然后,处理这些行的函数:

def hande_lines(lines):
    """A list of lines we care about."""
    return [line for line in lines if test_line(line) is not None]

以及处理文件的功能:

def handle_file(name):
    """Parse a file into a list of lines we care about."""
    with open(name) as f:
        return hande_lines(f)

第二个建议:写一个测试。要测试脚本,请将其包含在.py文件的底部(我们称此文件为“模块”):

if __name__=="__main__":
    # this is just test of the module
    file_name = "travel_plans.txt"
    for value in handle_file(file_name):
        print(value)

通过在与脚本(和测试文件)相同的目录中打开命令行并运行此命令来运行它,其中“myapp”是.py文件的名称:

python myapp.py

最后一点注意:编写测试的更好方法是使用assert语句,而不是使用print函数

if __name__=="__main__":
    # this is just test of the module
    file_name = "travel_plans.txt"
    result = handle_file(file_name):
    # make sure all the lines were found:
    assert len(result) == 6
    # make sure all the lines have the colon in them:
    assert all(":" in r for r in result)
    # finally, test a couple of the results that they are what we expect:
    assert result[0] == "Italy: Rome"
    assert result[-1] == "Austria: Vienna"

如果这些断言语句中的任何一个产生了AssertionError,那么您就知道您编写的代码正在做您不希望它做的事情

学习编写好的测试,这样你就知道你的代码正在做你想让它做的事情,这是一个很好的习惯

destination = []
with open("travel_plans.txt","r") as fileref:
    for line in fileref:
        row = line.strip()
        if ":" in row:
            destination.append(row)
print(destination)

对于一个小文件来说,任何比这更多的东西都可能是一种过度杀伤力

你可以把它做得更短

destination = [line.strip() for line in fileref if ":" in line]
print(destination)

相关问题 更多 >