我应该为任何单词的输入编写一个函数,以便在歌曲标题中搜索,然后返回包含该词的歌曲数量。如果没有找到任何单词,那么返回一份声明,说没有找到任何单词。我的输出正在运行elif语句,然后运行if语句。我会张贴我的前景是什么样子。
import csv
word_count = 0
with open("billboard_songs.csv") as data:
word = input("Enter any word: ")
for line in data:
line_strip = line.split(",")
if word.casefold() in line_strip[1]:
word_count += 1
print(word_count, "songs were found to contain", word.casefold(), "in this data set")
elif word_count == 1:
print("No songs were found to contain the words: ", word.casefold())当前产出:
没有发现任何歌曲中有这样的词:战争
没有发现任何歌曲中有这样的字眼:战争。
没有发现任何歌曲中有这样的字眼:战争。
没有发现任何歌曲中有这样的字眼:战争。
在这个数据集中发现了2首包含war的歌曲。
在这个数据集中发现了3首包含war的歌曲。
在这个数据集中发现了4首包含war的歌曲。
在这个数据集中发现了5首包含war的歌曲。
在这个数据集中发现了6首包含war的歌曲。
在这个数据集中发现7首歌曲包含了war。
在这个数据集中发现了8首包含war的歌曲
发布于 2020-02-21 18:59:39
代码有很多问题。
您应该使用的是您已经导入的,.
,.
if语句进行拆分,这实际上并没有达到您预期的效果。您应该做以下类似的事情:
import csv # Use it!将单词存储为变量:
word = input("Enter any word: ").casefold()希望你的CSV里面有头..。如果使用csv.DictReader,则使用它:
reader = csv.DictReader(open('billboard_songs.csv', 'r'))遍历CSV中的每首歌..。从line_strip[1]来看,你的歌词似乎在第二个领域。所以循环通过这些。您还应该设置一个变量来存储包含单词的歌曲的计数:
word_count = 0
for lyrics in reader['song_lyrics']: # replace 'song_lyrics' with your CSV header for the field with song lyrics
# Check the word is present在打印输出之前,先遍历完整的CSV。
if word in lyrics:
word_count += 1完成后,您可以使用if/else语句打印任何想要的输出:
if word_count == 0:
print('No songs were found to contain the words: {}'.format(word))
else:
# at least one set of lyrics had the word!
print('{} song(s) were found to contain {} in this data set'.format(word_count, word))或者,代替for循环和reader下面的所有内容,您可以使用sum,如下所示:
word_count = sum([word in lyrics for lyrics in reader['song_lyrics'])然后只需使用一个通用的print语句:
print('There were {} songs that contained the word: {}'.format(word_count, word))https://stackoverflow.com/questions/60344340
复制相似问题