【问题标题】:How to use a number in the first line of a .txt file to determine the number of words to be printed?如何使用 .txt 文件第一行中的数字来确定要打印的字数?
【发布时间】:2021-02-26 07:09:57
【问题描述】:

我有这个:

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 print(key) 打印 10 个单词而不是 55 个单词。 (功能是添加.txt文件的数字/数字单位)

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

【问题讨论】:

  • 我想你想写content = h.readline**s**(),否则你不会用for line in content:,对吗?
  • @alexzander ,之前我也尝试过使用 readlines(),但没有成功。我在这里使用了一个答案,我只需要用 'a = int (content)' 替换整个循环

标签: python readline readlines


【解决方案1】:

它读取两个数字。但它会将其读取为字符串"50"。然后遍历数字,将它们转换为ints 并将它们相加,即int("5") + int("0")。这给了你5(显然)。

所以只需将整个循环替换为

a = int(content)

如果您想检查该文件是否只有数字:

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

【讨论】:

    【解决方案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)
    

    【讨论】:

    • 非常感谢您的关注和回答问题!
    猜你喜欢
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 2020-06-12
    • 2013-08-15
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多