通过 Python 获取歌曲歌词

148 阅读2分钟

作为一名 Python 编程新手,您需要完成一项作业,使用 Python 编写一段代码来打印出歌曲《This Old Man》的歌词。歌词如下:

huake_00210_.jpg

This old man, he played one
He played knick-knack on my thumb
Knick-knack paddywhack, give your dog a bone
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
This old man came rolling home

This old man, he played two
He played knick-knack on my shoe
Knick-knack paddywhack, give your dog a bone
This old man came rolling home

…

This old man, he played ten
He played knick-knack once again
Knick-knack paddywhack, give your dog a bone
This old man came rolling home

您已经写出了以下代码,但它无法达到预期效果:

num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']
z=1

print "This old man, he played",(num)
print "He played knick-knack", (end)
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home"

2、解决方案

方法一:使用循环和切片

您可以使用 Python 中的循环和切片来遍历数字和结尾列表,并逐个组合打印出来。例如,您可以使用以下代码:

num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']

for i in range(len(num)):
    print("This old man, he played", num[i])
    print("He played knick-knack", end[i])
    print("Knick-knack paddywhack, give your dog a bone")
    print("This old man came rolling home")

    print()  # 空行

方法二:使用 zip() 函数

Python 中的 zip() 函数可以将多个列表组合成一个元组列表,您可以使用它来简化歌词的打印。例如,您可以使用以下代码:

num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']

for n, e in zip(num, end):
    print("This old man, he played", n)
    print("He played knick-knack", e)
    print("Knick-knack paddywhack, give your dog a bone")
    print("This old man came rolling home")

    print()  # 空行

方法三:使用 string.Template()

Python 中的 string.Template() 类允许您使用占位符来创建模板字符串,然后您可以用实际数据替换这些占位符来生成最终字符串。例如,您可以使用以下代码:

import string

template = string.Template("""
This old man, he played $num
He played knick-knack $end
Knick-knack paddywhack, give your dog a bone
This old man came rolling home
""")

num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']

for n, e in zip(num, end):
    result = template.substitute(num=n, end=e)
    print(result)

    print()  # 空行

使用以上方法之一,您就可以成功地用 Python 打印出《This Old Man》的歌词。