我有一个句子的文本文件。我需要随机读取字符串并在输出文件中输出字符串及其行号。我编写了以下代码:
ifile = open("test2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("Randomly Selected String ttt 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.
而不是手动递增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: %sn" % (i, myword))
输出当然会因随机性而变化。但是,运行可能会产生:
Line: 1 - Word: the
Line: 2 - Word: chocolate
Line: 3 - Word: I
Line: 4 - Word: was
Line: 5 - Word: clothes
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
这是你的错误的根源:
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 ttt Line Number")
for i, line in enumerate(ifile):
<do stuff with line and line number i>
试试这个
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