如何使用.txt文件第一行中的数字来确定要打印的字数?

2024-04-16 12:38:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个:

from random_word import RandomWords
import time

h = open('/home/rodrigo/Documents/num.txt', 'r')
content = h.readline()

print (content)


a = 0
for line in content:
    for i in line:
        if i.isdigit() == True:
            a += int(i)

r = RandomWords()
key = r.get_random_words()
time.sleep(3)
keys = key[:a]
time.sleep(1)
for key in keys:
    print(key)

我正在尝试读取并使用.txt文件第一行的数字。 在.txt文件中,我刚刚键入了数字:

50

但是,此代码只读取数字50的第一位数字,结果是函数print(key)只打印5个字(它应该打印50个字)

如果我将.txt文件更改为数字:55 {}打印10个单词,而不是55个单词。 (该函数用于添加.txt文件的数字/数字单位)

有人能帮忙吗?如何打印与.txt文件中键入的数字完全相等的字数


2条回答

content是一个字符串,您在第一个for循环中遍历字符串中的字符(并使用嵌套的for循环遍历单个字符字符串line一次)

如果您只需要一行代码,那么用以下代码替换第一个for循环应该可以:

 if content.isdigit() == True:
    a += int(content)

如果需要多行并分别添加,请将每行添加到如下列表:

from random_word import RandomWords
import time

h = open('/home/rodrigo/Documents/num.txt', 'r')
content = []
line = h.readline()
while line:
    content.append(line)
    line = h.readline()
print (content)


a = 0
for line in content:  # You only need one for loop.
    if line.isdigit() == True:
        a += int(i)

r = RandomWords()
key = r.get_random_words()
time.sleep(3)
keys = key[:a]
time.sleep(1)
for key in keys:
    print(key)

它读取两个数字。但是它把它读成一个字符串"50"。然后迭代这些数字,将它们转换为int并将它们相加,即int("5") + int("0")。这给了你5(显然)

因此,只需将整个循环替换为

a = int(content)

如果要检查文件是否只有数字:

try:
    a = int(content)
except ValueError:
    print("The content is not intiger")

相关问题 更多 >