如何读取文本文件并按相反顺序输出单词?python
因此,我正在编写一个代码,它读取文本并在屏幕上以相反的顺序输出单词,意思是如果原始文本是如何读取文本文件并按相反顺序输出单词?python,python,Python,因此,我正在编写一个代码,它读取文本并在屏幕上以相反的顺序输出单词,意思是如果原始文本是 你好,世界 你好吗 致: 你是怎么做到的 世界你好 我让它部分工作,问题是它在单个列中输出它,但我希望它在行中 代码是 for a in reversed(list(open("text.txt"))): for i in a: a = i.split() b = a[::-1] final_string = '' for i i
你好,世界
你好吗
致:
你是怎么做到的
世界你好
我让它部分工作,问题是它在单个列中输出它,但我希望它在行中
代码是
for a in reversed(list(open("text.txt"))):
for i in a:
a = i.split()
b = a[::-1]
final_string = ''
for i in b:
final_string += i + ' '
print(final_string)
您有一个循环太多:
for a in reversed(list(open("text.txt"))):
for i in a:
第一个循环以相反的顺序生成文件中的行,因此a
被绑定到每一行。然后的第二个循环遍历该行中的每个字符。然后继续“反转”该字符(或当该字符为空格或换行符时为空列表)
您已经对文件使用了reversed
,您也可以对行使用它;结合:
或者更简洁地说:
print(*(' '.join(l.split()[::-1]) for l in reversed(list(open('text.txt')))), sep='\n')
演示:
当使用有意义的变量名时,它使代码更容易理解。啊,谢谢,第一个是正确的,现在我只有一个问题,exactli reversed_words=''。join(reversed(words))做什么,如果你能向noob解释的话。我真的很感激that@AleksČerneka:反向(单词)
为您提供反向单词''.join()
获取单词并将它们连接在一起,将'
放在每个单词之间。我现在明白了。很抱歉。
print(*(' '.join(l.split()[::-1]) for l in reversed(list(open('text.txt')))), sep='\n')
>>> with open('text.txt', 'w') as fo:
... fo.write('''\
... hello world
... how are you
... ''')
...
24
>>> for line in reversed(list(open("text.txt"))):
... words = line.split()
... reversed_words = ' '.join(reversed(words))
... print(reversed_words)
...
you are how
world hello
>>> print(*(' '.join(l.split()[::-1]) for l in reversed(list(open('text.txt')))), sep='\n')
you are how
world hello