我有一个句子的文本文件。我需要随机读取字符串并在输出文件中输出字符串及其行号。我写了以下代码:
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.
答案 0 :(得分:1)
您可以使用i
,而不是手动递增enumerate()
。代码的问题在于您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
答案 1 :(得分:0)
这是你的错误来源:
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>
答案 2 :(得分:0)
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
答案 3 :(得分:0)
试试这个
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)
答案 4 :(得分:0)
另一个解决方案!添加了一个计算行数的计数器,并将计数作为行输出。
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