如何打印作为新记录打印的字符串的每个单词?

时间:2013-09-20 13:02:02

标签: python-3.x

我是Python新手。 我输入了这种格式

Harry is American Harry is American Harry is American Harry is American
Harry is American Harry is American Harry is American Harry is American
Harry is American Harry is American Harry is American Harry is American

我的输出应该是这样的

Harry, 1
is, 1
American, 1
Harry, 1
is, 1
American, 1
....

你能告诉我解决方案......

我正在尝试下面的代码(我的代码甚至没有更接近解决方案)。

import sys
import re
inp = open('menu.bak', "r")
outp = open('word.txt',"w")
for line in inp:
  counts = len(re.findall(r'\w+', line))
  new = ''.join(line)
  print(new[0])
  print(new[1])
inp.close()
outp.close()

谢谢, Gokul S

1 个答案:

答案 0 :(得分:1)

import re
inp = open('menu.bak', "r")
outp = open('word.txt',"w")
for line in inp:
  for word in line.split():
    outp.write(str(word) + "," + "1" + '\n')
inp.close()
outp.close()