繁体   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