解析带有冒号的行中的单词(简单的初学者任务)

huangapple go评论67阅读模式
英文:

Parse words from lines with colons (simple beginner assignment)

问题

使用存储在 "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)

是否有更好的方法来获得相同的输出?

英文:

Create a list called destination using the data stored in "travel_plans.txt". Each element of the list should contain a line from the file that lists a country and cities inside that country.

The "travel_plans.txt" contains :

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!

So far I have managed to write the following :

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

Is there a better way of getting the same output?

答案1

得分: 2

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 = 
print(destination)
英文:
destination = []
with open("travel_plans.txt","r") as fileref:
    for line in fileref:
        row = line.strip()
        if ":" in row:
            destination.append(row)
print(destination)

For a small file, anything more than this would probably be an overkill.

You could make this even shorter.

destination = 
print(destination)

答案2

得分: 1

接受的答案非常好。由于您正在学习,我有一些建议。

首先,您可以考虑使用稍微更具Python风格(通常指“可读性”)的方法,其中包括将其拆分成多个函数。

第一个示例中的第二行被称为“文档字符串”。它向代码的其他读者(包括提醒未来的您)解释代码的功能。

然后是处理行的函数:

def handle_lines(lines):
    """我们关心的行的列表。"""
    return 

以及处理文件的函数:

def handle_file(name):
    """将文件解析为我们关心的行的列表。"""
    with open(name) as f:
        return handle_lines(f)

第二个建议是编写测试。要测试脚本,请在.py文件的底部包括以下内容(我们将这个文件称为“模块”):

if __name__ == "__main__":
    # 这只是模块的测试
    file_name = "travel_plans.txt"
    for value in handle_file(file_name):
        print(value)

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

python myapp.py

最后一点说明:与其使用print函数,编写测试的更好方法是使用assert语句。

if __name__ == "__main__":
    # 这只是模块的测试
    file_name = "travel_plans.txt"
    result = handle_file(file_name)
    # 确保找到所有行:
    assert len(result) == 6
    # 确保所有行都包含冒号:
    assert all(":" in r for r in result)
    # 最后,测试一些结果,以确保它们是我们期望的:
    assert result[0] == "Italy: Rome"
    assert result[-1] == "Austria: Vienna"

如果这些assert语句中的任何一个产生AssertionError,那么您就知道您编写的代码正在执行一些不希望它执行的操作。

学会编写良好的测试,以便知道您的代码是否按您的意愿执行,是一个非常好的习惯,应立即采纳。

英文:

The accepted answer is pretty good. I have a few other suggestions since you are learning.

First, you might consider a slightly more pythonic (by which it is usually meant "readable") approach, which could include breaking this into multiple functions.

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

The second line in the above is called the "docstring". It explains to other readers of your code (including reminding future you) what the code does.

Then your function for handling the lines:

def hande_lines(lines):
    """A list of lines we care about."""
    return 

And your function for handling the file:

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

Second suggestion: write a test. To test the script, include this at the bottom of your .py file (we call this file a "module"):

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

Run it by opening the command line in the same directory as your script (and test file), and running this command, where "myapp" is the name of your .py file:

python myapp.py

One final note: rather then using the print function, a much better way to write your tests is to use assert statements.

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"

If any of these assert statements produce an AssertionError, then you know the code you wrote is doing something you don't want it to do.

Learning to write good tests, so that you know your code is doing what you want it to do, is a very good habit to get into right away.

huangapple
  • 本文由 发表于 2020年1月6日 17:57:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定