簡體   English   中英

列出清單並放入字符串

[英]Take a list and make it into strings

基本上,我試圖制作一個隨機的單詞生成器,但我希望能夠將單詞復制並粘貼到python中,然后將其更改為字符串,以便我可以隨機選擇。

我要使用的代碼與此類似:

import random
a = ["Cat", "DOG", "MOM"]
print(random.choice(a))

我是python新手,所以如果有更簡單的方法來制作隨機字生成器,請告訴我。 它將有兩個生成器,一個用於動詞,一個用於名詞。

詞是字符串。 這段代碼對我來說看起來不錯。 但是,如果您要提高效率,請嘗試以下操作:


verbs.txt

run play skip jump

nouns.txt

cat book rope rock

script.py

verbs = open('verbs.txt').read().split(' ')
verb = random.choice(verbs)

nouns = open('nouns.txt').read().split(' ')
noun = random.choice(nouns)

願您可以閱讀文件以讀取單詞並按如下方式處理它們:

通道:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

讀取單詞並將其拆分為列表並隨機打印:

import re
import random

fd = open('data.txt')
lines = [i.strip() for i in fd]

words = []
for line in lines:
  for word in ''.join(re.split('[,;.!]', line)).split(' '):
    words.append(word)

# pick up 5 words
for i in range(5):
  print random.choice(words)

但我不知道你如何獲得動詞或名詞...可能會有所幫助

最好的方法是將一系列純文本單詞保存到文本文件中,然后以編程方式將文件讀取到python中。

以以下示例文本文件(在與python程序相同的目錄中保存為“ words.txt”):

cat dog cow man cheese

您將使用以下代碼將其讀入python並將其存儲為字符串列表

infile = open("words.txt", 'r') #open the file for reading
a = infile.read().strip().split(" ") #read in the file and divide into words by splitting on spaces
print random.choice(a) #print a random word from the file
infile.close() #close the file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM