【问题标题】:to import txt file of words and print words in separate lines导入单词的txt文件并在单独的行中打印单词
【发布时间】:2019-01-30 13:51:56
【问题描述】:

我有一个包含 40 个单词的文本文件,例如one two three ... forty。所有单词相互之间,不包括逗号。我需要将它们打印到屏幕或彼此相邻的另一个文件中,用逗号分隔(例如:one, two, three, ...),并让它们每十 (10) 个或七 (7) 个单词包装一次。 这是我的代码,无法正常工作:

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')

有人可以帮忙吗? 谢谢。

【问题讨论】:

  • 您能提供一个示例 I/O 吗?
  • 等等。 and also have them wrap up 每十 (10) 或七 (7) 个字。 是什么意思?
  • 输出应该是:一、二、三、四、五、六、七、八、九、十(第一行),然后:十一、十二、...二十(第二行)行),依此类推...您的代码 user5173426 提供的不起作用。
  • 编辑了我的答案。

标签: python string printing line


【解决方案1】:

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, 

【讨论】:

  • 谢谢。您的代码对我帮助很大,尽管我未能传达我真正想说的内容。我的意思不是以文本窗口的当前大小换行,而是每十个单词引入一个回车 [ENTER],这样文本窗口中的每一行都会有十个单词。但是,我打算将您的代码合并到我的程序中。它以不同的方式完成工作。谢谢。
  • @G.Trialonis 很高兴它对您有所帮助,您可以通过单击勾选标记来标记答案以接受它,干杯:)
【解决方案2】:

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

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

如果你想用 7 个单词包装它们,你可以使用如下函数:

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

>>> grouped(word, 7)

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    相关资源
    最近更新 更多