Python:如何将可变数量的列表写入新文件的一行

时间:2013-10-26 15:46:46

标签: python list

我有一个输出,其中每行包含一个列表,每个列表包含连字符后的一个单词。 它看起来像这样:

['I']
['am']
['a']
['man.']
['I']
['would']
['like']
['to']
['find']
['a']
['so','lu','tion.'] 
(let's say it's hyphenated like this, I'm not a native English speaker)

etc.

现在,我想要做的是将此输出写入新的.txt文件,但每个句子(当列表中的项包含一个点时句子结束)必须写入换行符。我想将以下结果写入此.txt文件:

I am a man.
I would like to find a so,lu,tion.
etc.

所有这些之前的编码如下:

with open('file.txt','r') as f:
    for line in f:
        for word in line.split():
            if h_en.syllables(word)!=[]:
                h_en.syllables (word)
            else:
                print ([word])

我想要的结果是一个文件,每行包含一个句子。 句子的每个单词都用连字符表示。

有什么建议吗?

非常感谢你。

3 个答案:

答案 0 :(得分:2)

像这样基本的东西似乎满足了你的需要:

def write_sentences(filename, *word_lists):
  with open(filename, "w") as f:
    sentence = []
    for word_list in word_lists:
      word = ",".join(word_list) ##last edit
      sentence.append(word)
      if word.endswith("."):
        f.write(" ".join(sentence))
        f.write("\n")
        sentence = []

使用输出文件名输入write_sentences函数,然后输入每个单词 列出为参数。如果您有单词列表列表(例如[['I'], ['am'], ...]),则可以在调用时使用* 传递一切的功能。

编辑:更改为使其能够使用最新的答案编辑(单词列表中包含多个单词)

答案 1 :(得分:1)

这个简短的正则表达式在MULTILINE模式下编译时可以实现所需:

>>> regex = re.compile("\[([a-zA-Z\s]*\.?)\]$",re.MULTILINE)`
>>> a = regex.findall(string)
>>> a
[u'I', u'am', u'a man.', u'I', u'would like', u'to find', u'a solution.']

现在您只需操作列表,直到获得想要的结果。下面是一个例子,但有更多方法可以做到:

>>> b = ' '.join(a)
>>> b
'I am a real man. I want a solution.'
>>> c = re.sub('\.','.\n',b)
>>> print(c)
'I am a real man.'
' I want a solution.'
>>> with open("result.txt", "wt") as f:
        f.write(c)

答案 2 :(得分:0)

words = [['I'],['am'],['a'],['man.'],['I'],['would'],['like'],['to'],['find'],['a'],['so','lu','tion.']]

text = "".join(
    "".join(item) + ("\n" if item[-1].endswith(".") else " ") 
        for item in words)

with open("out.txt", "wt") as f:
    f.write(text)