提问人:Sash Read 提问时间:3/29/2023 更新时间:3/29/2023 访问量:39
列表没有按照我想要的方式打印出来。我需要帮助来弄清楚如何正确打印它
List is not printing out the way I want it to. I need help to figure out how to print it correctly
问:
我应该拿单篇文章,每月整理一次(有 11 个月),然后打印列表。我已将每个单词附加到列表 wordsList 中;但是它没有按照我需要的方式打印出来,而且我不确定如何让它做我想做的事。下面是代码的一部分。(我放了两个#,一个在下面,一个在似乎是问题的一部分上面。
def process_file(filename):
file = open(filename, 'r', encoding="utf-8")
nextL = file.readline()
wordsList = [[],[],[],[],[],[],[],[],[],[],[]]
while nextL != '':
if nextL[0:3] == 'URL':
url = nextL
get_week(url)
nextL = file.readline()
else:
for i in nextL:
while nextL[0:3] != 'URL':
aux = ''
nextL = nextL.split()
for i in nextL:
a = i.strip('—;“.”:!,?')
aux += a
wordsList[get_week(url)].append(aux.lower())
#
weekly_tokens = print(wordsList)
#
aux = ''
nextL = file.readline()
file.close()
return weekly_tokens
def main():
process_file(get_filename())
#process_file(filename) ?
#print(weekly_tokens) ?
main()
下面是输出。我只想打印出最后一个列表,而不是下面发生的事情:[['behsud', 'afghanistan', ''', 'the', 'first'], [], ['it's', 'the', 'rare', 'wine'], [], []]。我怎样才能让它只打印出那个?(它不应该输出前 8 行)
Enter a file name: articles.txt
[['behsud'], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan'], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', ''], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the'], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s'], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s', 'the'], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s', 'the', 'rare'], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s', 'the', 'rare', 'wine'], [], [], [], [], [], [], [], []]
其他一切都工作正常,我只想显示完成的列表,而不是它的早期版本。(另外,我是初学者,如果我的代码很糟糕,很抱歉)。如果你能向我解释我做错了什么以及如何解决问题,那就太好了。
答:
1赞
M.G.Poirot
3/29/2023
#1
在 Python 中,print 函数不返回任何内容,它只是将其参数直接打印到控制台。 因此,您看到打印的八行的原因是 print 语句位于 for 循环中。再往上看几层,解决方案如下:
def process_file(filename):
file = open(filename, 'r', encoding="utf-8")
nextL = file.readline()
wordsList = [[],[],[],[],[],[],[],[],[],[],[]]
while nextL != '':
if nextL[0:3] == 'URL':
url = nextL
get_week(url)
nextL = file.readline()
else:
for i in nextL:
while nextL[0:3] != 'URL':
nextL = nextL.split()
for i in nextL:
aux = ''
a = i.strip('—;“.”:!,?')
aux += a
wordsList[get_week(url)].append(aux.lower())
nextL = file.readline()
file.close()
print(wordsList)
如果它解决了您的问题,请告诉我。我无法运行测试。
评论
0赞
Sash Read
3/29/2023
不幸的是,当我这样做时,它不会打印出任何东西。我的目标是返回变量 weekly_tokens,它应该打印列表 wordsList。谢谢你的帮助,虽然:)
0赞
M.G.Poirot
3/30/2023
在您的示例中,打印的内容是 ,所以很好奇为什么在运行我的解决方案时没有显示任何内容。在您的示例中,因为它是由函数分配的。因此,如果要返回,只需在 的末尾添加,然后调用其调用的输出。words_list
weekly_tokens
None
print
words_list
return word_list
process_file
print
评论