我一直试图弄清楚如何将一个文本文件随机选取一个单词,然后从3个不同的文本文件中将它们全部打印成1行,但我不能将它放在一行中?它每次都把它换成新的一行?这些单词都在文本文件的列中。使用PYTHON IDLE加入IM !!
###############
import random
import time #Importing so some bits of code works
import sys
###############
#The main game and generator
def main():
#Gets text files from the folder and randomly picks a line of the text
with open("column1.txt") as A:
A = random.choice(list(A))
with open("column2.txt") as B:
B = random.choice(list(B))
with open("column3.txt") as C:
C = random.choice(list(C))
print("\nThou\n"A+B+C)
time.sleep(2)
print("Restarting...\n")
menu()
#Menu System
def menu():
print("===Menu===")
print("Choose 1 to start the abuse generator.")
print("Choose 2 to exit.")
choice = input("Please choose one: ")
if choice == "1":
main()
elif choice == "2":
sys.exit()
else:
print("Error!")
#Go's to the menu that is defined as menu above
menu()
这是输出:
===Menu===
Choose 1 to start the abuse generator.
Choose 2 to exit.
Please choose one: 1
Thou
lumpish
tdizzy-eyed
thugger-mugger
Restarting...
这是column1:
artless
bawdy
beslubbering
bootless
churlish
cockered
clouted
craven
currish
dankish
dissembling
droning
errant
fawning
fobbing
froward
frothy
gleeking
goatish
gorbellied
impertinent
infectious
jarring
loggerheaded
lumpish
mammering
mangled
mewling
paunchy
pribbling
puking
puny
quailing
rank
reeky
roguish
ruttish
saucy
spleeny
spongy
surly
tottering
unmuzzled
vain
venomed
villainous
warped
wayward
weedy
yeasty
答案 0 :(得分:0)
首先,语法错误:
print("\nThou\n"A+B+C)
应该是
print("\nThou\n"+A+B+C)
示例代码:
A = "Some random Text1"
B = "Some random Text2"
C = "Some random Text3"
print("\nThou\n",A,B,C)
输出:
Thou
Some random Text1 Some random Text2 Some random Text3
如果您对此有任何其他疑问,请与我们联系
答案 1 :(得分:0)
要将多行字符串放在一行上,您可以执行
with open("column1.txt") as A:
A = random.choice(list(A))
with open("column2.txt") as B:
B = random.choice(list(B))
with open("column3.txt") as C:
C = random.choice(list(C))
print " ".join((A + B + C).splitlines())
str.splitlines()
创建一个字符串列表,每个字符串都是多行字符串的一行。删除换行符,一行中的多个单词不会拆分()。
答案 2 :(得分:-1)
听起来你需要将文件拆分成新行字符的字符串:
with open("column1.txt") as A:
A = random.choice(A.read().split('\n'))
with open("column2.txt") as B:
B = random.choice(B.read().split('\n'))
with open("column3.txt") as C:
C = random.choice(C.read().split('\n'))
您可能还希望以不同方式调用print语句,以便添加空格:
print("\nThou\n", A, B, C)
要使用python 2,你需要使用from __future__ import print_function
或省略大括号。