简体   繁体   English

Python readlines()将行分为两部分

[英]Python readlines() splits line into two

I'm reading lines from a text file. 我正在从文本文件中读取行。 In the text file there is a single word in each line. 在文本文件中,每行只有一个单词。 I can read and print the word from the file, but not the whole word is printed out on one line. 我可以从文件中读取并打印单词,但不是整个单词都打印在一行上。 The word is split into two. 这个词分为两个部分。 The letters of the printed word are mixed. 印刷单词的字母混合在一起。

Here is my code: 这是我的代码:

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()

How can I display one word on a line? 如何在一行上显示一个单词?

EDIT: 编辑:

this is the content of the text file: 这是文本文件的内容:

pinapple    
pear    
strawberry    
cherry    
papaya  

The script should print one of these words (with their letters mixed) like this: 脚本应打印以下单词之一(字母混合在一起):

erpa

(This would be the equivalent of pear) (这相当于梨)

Right now it is displayed like this: 现在它显示如下:

erp  
a

that's because you're also shuffling the line termination chars that readlines or line iterators include in the line. 那是因为您还要改写行中的readlines或line迭代器的行终止字符。 Use strip() to get rid of them (or rstrip() ) 使用strip()摆脱它们(或rstrip()

Do it like this (avoid readlines BTW): 这样做(避免readlines顺便说一句):

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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM