[英]Python: how to write a variable number of lists to a line of a new file
我有一個輸出,每一行包含一個列表,每個列表包含一個連字符后的一個單詞。 看起來像這樣:
['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])
我想要的結果是一個在每一行包含一個句子的文件。 句子中的每個單詞都由連字符表示。
有什么建議么?
非常感謝。
像這樣的基本東西似乎可以滿足您的需求:
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'], ...]
),則可以在調用函數以傳遞所有內容時使用*
。
編輯 :已更改,使其可以與答案的最新編輯一起使用(單詞列表中有多個單詞)
當在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)
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.