【问题标题】:Reading and print string x times读取并打印字符串 x 次
【发布时间】:2019-06-05 11:04:06
【问题描述】:

我有一个作业,我有一个文本文件,每行都有一个单词,形成一个字符串。在某些行上,我必须打印字符串的次数,以逗号和空格分隔,并以句点结束

例如:

Darth
Maul
is
a
bad
person
3

那么应该是:Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.

到目前为止,我很困惑,我很熟悉如何逐行读取文件,我想我已经将单词放在一个列表中,并确定数字何时会多次迭代该列表。

到目前为止我有:

TEXT = input 'sith.txt'
words = []

with open(TEXT, 'r') as f:
    line = f.readline()
    for word in line:
        if string in word //is a string not an int
            words.append(string)
        else //print words + ', '

在这之后,我几乎陷入了困境。有没有人可以指出我正确的方向?

【问题讨论】:

  • 如果行是This/should/be/written/3/times/3怎么办?
  • @tobias_k 好吧,在这种情况下,分配不是这样。
  • 我的意思是:数字是否总是在最后一行,或者任何一行都可以是数字,这意味着前面的行(从最后一个数字开始)应该经常重复?
  • @tobias_k 我想这取决于你如何编写程序,但在这种情况下,是的。

标签: python file for-loop if-statement readlines


【解决方案1】:

您可以在 print 中使用连接和 end 参数来以更少的行数完成此操作。

lines = open("input.txt", "r").read().splitlines()
data, number = " ".join(lines[:-1]), int(lines[-1])

print(", ".join([data]*number), end=". ")

哪些输出:

Darth Maul 是个坏人,Darth Maul 是个坏人,Darth Maul 是个坏人。

【讨论】:

    【解决方案2】:

    示例文件:filename=text.txt

    Darth
    Maul
    is
    a
    bad
    person
    3
    Foo bar
    baz
    bla
    5
    another
    demo
    2
    

    代码:

    import re
    
    with open('text.txt') as fd:
        data = fd.read()
    
    regex = re.compile(r'([^\d]+)(\d+)', re.DOTALL|re.MULTILINE)
    for text, repeat in regex.findall(data):
        repeat = int(repeat)
        text = text.strip().replace('\n', ' ')
        print(', '.join([text] * repeat))
    

    输出:

    Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person
    Foo bar baz bla, Foo bar baz bla, Foo bar baz bla, Foo bar baz bla, Foo bar baz bla
    another demo, another demo
    

    【讨论】:

    • 别忘了关闭你的文件。你应该使用with open,这样就不用记住了。
    • 我认为你需要添加 end="."在您的打印声明中。我认为这句话应该以“。”结尾
    • @GrantWilliams 添加 end='.' 将使这 3 行都在一行中。如果句号非常重要,可以像这样连接结果:print(', '.join([text] * repeat) + '.')
    【解决方案3】:
    # Read the TXT file into a list and strip whitespace from each line
    with open('sith.txt', 'r') as infile:
        contents = [i.strip() for i in infile.readlines()]
    
    # Get number of times to repeat phrase using the .pop method which returns the value at the index of an item and removes it from the list
    repeat = int(contents.pop(-1))
    
    # Create the phrase to repeat using the range() function and list comprehension
    phrase = [' '.join(contents) for _ in range(repeat)]
    
    # Join the phrases together with a comma and print the output
    output = ', '.join(phrase)
    print(output)
    

    【讨论】:

      【解决方案4】:

      如果保证整数出现在末尾,则可以迭代直到达到 int。如果可以有多个单词块,每个单词块的末尾都有一个 int,您可以逐行迭代并尝试将该行转换为 int。

      TEXT = 'sith.txt'
      words = []
      multiple = 0
      
      with open(TEXT, 'r') as f:
          # iterate through every line
          for line in f:
              # get rid of the '\n' at the end
              line = line.strip()
      
              # try casting the line as an int. If it's not an integer, it will raise a ValueError and skip to the except block
              try:
                  multiple = int(line)
                  for i in range(multiple):
                      print(' '.join(words), end=', ')
                  print() # for a new line at the end
                  words = [] # reset words for new chunk
      
              # This except block gets run every time int() casting fails on a string
              except ValueError:
                  words.append(line)
      

      【讨论】:

        【解决方案5】:
        TEXT = 'sith.txt'                                      #your filename was off a bit
        words = []
        with open(TEXT, 'r') as f:                             #open it
            line = f.readlines()                               #read in the contents, save to "line"
            for word in line:                                  #for each word in the doc...
                if not word[:-1].isdigit():                    #if it's a word (we exclude last char because it's always "\n"
                    words.append(word[:-1])                    #put it in the list
                else:                              
                    for i in range(int(word)-1):               #we want to print it n-1 times with commas and once with the period.
                        print(" ".join(words), end=", ")       #print with commas.
                    print(" ".join(words), end=".\n")          #print with period.
        

        这给了我们...

        【讨论】:

          【解决方案6】:

          KuboMD 和我有类似的答案

          TEXT = 'sith.txt'
          
          with open(TEXT, 'r') as file:
              words = []
              for line in file:
                  line = line.strip()
                  if line.isdigit():
                      segment = " ".join(words)
                      for i in range (int(line) - 1):
                         print(segment, sep =", ")
                      print(segment + ".\n")
                  else:
                      segment.append(line)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-02-28
            • 1970-01-01
            • 2012-06-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多