如何将单个单词合并为一行

时间:2018-06-21 17:51:51

标签: python list words

我已完成以下操作:

  1. 打开的文件
  2. 拆分为列表
  3. 使用for循环进行反向循环
  4. 输出如下:

# I am interested in position Dualer Master (w/m) im Bereich "Next Generation B2B

B2B
Generation
"Next
Bereich
im
(w/m)
Master
Dualer
position
in
interested
am
I

现在我需要将这些单词重新合并为一行,有帮助吗?

下面是我的代码:

fh = open('new.txt', 'r')
for file in fh :
    line = file.split()
    for word in reversed(line):
        print(word)

1 个答案:

答案 0 :(得分:0)

您的代码可以生成如下输出:

B2B
Generation
"Next
Bereich
im
(w/m)
Master
Dualer
position
in
interested
am
I

通过格式化print函数,您可以重新合并输出。喜欢

fh = open('new.txt', 'r')
for file in fh :
    line = file.split()
    for word in reversed(line):
        print(word, end=' ')

如果要将此字符串用作重用,则可以连接单词。 完整代码

fh = open('new.txt', 'r')
oneLineString = ''
for file in fh :
    line = file.split()
    for word in reversed(line):
        print(word)
        oneLineString+= (word + " ")
print(oneLineString)

输出:

B2B
Generation
"Next
Bereich
im
(w/m)
Master
Dualer
position
in
interested
am
I
B2B Generation "Next Bereich im (w/m) Master Dualer position in interested am I