Python readlines()将行拆分为两行

Pap*_*apT 2 python python-3.x

我正在从文本文件中读取行.在文本文件中,每行中只有一个单词.我可以从文件中读取和打印单词,但不是整行都打印出来.这个词分为两个.印刷字母的字母是混合的.

这是我的代码:

import random
fruitlist = open('fruits.txt', 'r')

reading_line = fruitlist.readlines()
word = random.choice(reading_line)
mixed_word = ''.join(random.sample(word,len(word)))

print(mixed_word)

fruitlist.close()
Run Code Online (Sandbox Code Playgroud)

如何在一行上显示一个单词?

编辑:

这是文本文件的内容:

pinapple    
pear    
strawberry    
cherry    
papaya  
Run Code Online (Sandbox Code Playgroud)

脚本应该打印其中一个单词(其字母混合),如下所示:

erpa
Run Code Online (Sandbox Code Playgroud)

(这相当于梨)

现在它显示如下:

erp  
a
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 5

那是因为你也在洗牌行终止字符readlines或行迭代器包含在行中.使用strip()摆脱他们的(或rstrip())

这样做(避免readlinesBTW):

with open('fruits.txt', 'r') as fruitlist:
    reading_line = [x.strip() for x in fruitlist]
    word = random.choice(reading_line)
    mixed_word = ''.join(random.sample(word,len(word)))
Run Code Online (Sandbox Code Playgroud)