代码之家  ›  专栏  ›  技术社区  ›  G. Trialonis

导入文字的txt文件并以单独的行打印文字

  •  1
  • G. Trialonis  · 技术社区  · 7 年前

    我有一个包含40个单词的文本文件,例如。 one two three ... forty ,不包括逗号。我需要将它们逐个打印到屏幕或另一个文件中,并用逗号分隔(例如: one, two, three, 这是我的代码,无法工作:

    import textwrap
    flag = 1
    comma = ', '
    
    with open('drop_words.txt', encoding='utf-8') as file:
        content = file.read()
        content = content.split()
        words = comma.join(content)
        if len(content)%7 == 0:
            print(words, '\n')
    

    非常感谢。

    2 回复  |  直到 7 年前
        1
  •  1
  •   DirtyBit    7 年前

    drop_words.txt:

    one
    two
    three
    four
    

    然后:

    with open('drop_words.txt', encoding='utf-8') as file:
        content = file.readlines()
        # you may also want to remove empty lines
        content = [l.strip() for l in content if l.strip()]
        print(", ".join(content), end = '')
    

    输出:

    one, two, three, four
    

    如果把这些词包装在一起,你的意思是 ,你可以用 grouper 比如:

    import itertools as IT
    
    def grouper(n, iterable):
        iterable = iter(iterable)
        return iter(lambda: list(IT.islice(iterable, n)), [])
    
    with open('list.txt', encoding='utf-8') as file:
        content = file.readlines()
        content = [l.strip() for l in content if l.strip()]
        print(", ".join(content))
        grouping = ", ".join(content)
        #creating a list out of the comma separated string
        grouping = grouping.split(",")
        # grouping the two elements
        print(list(grouper(2, list(grouping))))
    

    one, two, three, four
    [['one', ' two'], [' three', ' four']]
    

    编辑2:

    OP提到了连续10位数字的组合

    wrap = 0
    newLine = True
    with open('list.txt', encoding='utf-8') as file:
        content = file.readlines()
        # you may also want to remove empty lines
        content = [l.strip() for l in content if l.strip()]
        for line in content:
            if wrap < 10:
                print("{}, " .format(line), end = '')
            else:
                if newLine:
                    print("\n")
                    newLine = not newLine
                print("{}, ".format(line), end='')
            wrap += 1
    

    one, two, three, four, five, six, seven, eight, nine, ten, 
    
    eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, 
    
        2
  •  0
  •   Julien Briand    7 年前

    这可以完成打印名称的工作:

    with open('drop_words.txt', encoding='utf-8') as f:
        words = [line for line.strip() in f]
        print(','.join(words))
    

    def grouped(iterable, n):
        return zip(*[iter(iterable)]*n)
    
    >>> grouped(word, 7)