簡體   English   中英

從txt.file隨機生成單詞(Python)

[英]Randomly Generate a Word from a txt.file (Python)

我有一個句子的文本文件。 我需要隨機讀取字符串,然后在輸出文件中輸出字符串及其行號。 我寫了以下代碼:

ifile = open("test2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("Randomly Selected String \t\t\t Line Number")

import random 

i=0

for lines in ifile.readline():

  line = lines[i] 

  words = line.split() 
  myword = random.choice(words)

  otfile.write(myword)
  otfile.write(str(i))
  i +=1
  otfile.write("\n") 

但是我只得到一個字符,沒有行號。 我一直在嘗試更改代碼,但我只是在創建錯誤。 有任何想法嗎?

(編輯)Test2.txt具有以下句子:

Brooklyn is the best place on Earth.
I had chocolate ice cream today.
I ate all the cookies in the cookie jar.
Today was a no good very bad day.
He got his clothes dirty playing outside.

您可以使用enumerate()代替手動遞增i 代碼的問題是您執行line = lines[i] 您正在將字符放在i位置並將其分配給line

for i, line in enumerate(ifile.readlines(), start=1):
    words = line.split()
    myword = random.choice(words)

    otfile.write("Line: %d - Word: %s\n" % (i, myword))

當然,輸出隨隨機性而變化。 但是,運行可能會產生:

Line: 1 - Word: the
Line: 2 - Word: chocolate
Line: 3 - Word: I
Line: 4 - Word: was
Line: 5 - Word: clothes

這是您的錯誤的來源:

for lines in ifile.readline():
    line = lines[i] 

您可以清理代碼的多個方面。 問題是您要遍歷for循環中文本文件的一行 ,即ifile.readline()的值是一個字符串! 因此,當您這樣做時:

for lines in ifile.readline():

循環變量lines遍歷文件第一行的各個字符。 我不確定您的意圖是:

line = lines[i]

但我只是將其刪除。 您只需使用for循環即可直接逐行直接遍歷文件處理程序:

f = open('my_file.txt')

for line in f:
    words = line.split()
    < do something with words >

另外,我還要指出,您的代碼有幾個方面應該解決。 使用enumerate而不是明確地跟蹤索引變量i是一種潛在的改進,就像使用with語句打開文件一樣。 您的代碼可能應該像這樣開始:

with open("test2.txt", "r") as ifile, open("OUT3.txt", "w") as otfile:
    otfile.write("Randomly Selected String \t\t\t Line Number")

    for i, line in enumerate(ifile):
        <do stuff with line and line number i>
i=1
for lines in ifile:
  print(lines)
  words = lines.strip().split()
  print(words)
  myword = random.choice(words)
  print(myword[random.randrange(0, len(myword))])
  myword = myword[random.randrange(0, len(myword))]  # chr , need str Comment this line

嘗試這個

with open('test2.txt') as f:
    lines = f.readlines()
    for line in lines:
        words = line.split(' ')
        myword = random.choice([x for x in words])
        print ">"+str(myword)

另一個解決方案! 添加了一個計數器,用於對行數進行計數並將計數輸出為行。

ifile = open("text2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("")
lst = []
import random
count = 1 # count the number of lines. Starts at 1.
for lines in ifile.readlines():
   words = lines.split()
   lst.extend(words) # add all the words to a list using .extend method
   myword = random.choice(lst)
   otfile.write("Line:{} Word: {} ".format(count, myword))
   count += 1

出: Line:1 Word: the Line:2 Word: icecream Line:3 Word: chocolate Line:4 Word: the Line:5 Word: today. Line:6 Word: bad Line:1 Word: the Line:2 Word: icecream Line:3 Word: chocolate Line:4 Word: the Line:5 Word: today. Line:6 Word: bad

暫無
暫無

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

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