[英]How to create sentences from a list of words in a file
我有一个csv
文件中的单词列表,每个单词在单独的一行中。 我想读取 15 行并将它们连接成一个句子,然后将它们写入一个新的csv
文件。 然后对接下来的 15 行重复该过程,并在新行中添加新句子,直到所有单词都用完为止。
我已经能够在 中创建一个单词列表,但是由于我是 python 的新手,我不知道如何遍历每个给定的行数并将一个句子连接到一个新文件中。
将不胜感激任何帮助。
我使用以下代码从包含大量文本的文件中创建单词列表:
with open("outfile11.csv", encoding = 'UTF_8') as f:
for line in f:
for word in line.split():
print(word)
with open("words.csv","a", encoding = 'UTF_8') as f1:
f1.write(word + "\n")
然后我使用以下代码从创建的列表文件中删除任何空行:
with open("words.csv","r", encoding='UTF_8') as f, open("cleanedWords.csv","w", encoding='UTF_8') as outfile:
for i in f.readlines():
if not i.rstrip():
continue
if i:
outfile.write(i)
如果您的 outfile.csv 中的每一行都是一个单词,那么这可以在您的第二个代码示例中简单地实现。
with open("words.csv", encoding='UTF_8') as f:
# Create a txt file (or what ever type you want)
with open('sentences.txt', "a", encoding='UTF_8') as sent:
# declare an empty list
words = []
# loop through lines
for line in f:
# add word to the word list
# replace the line break with an empty string
words.append(line.replace('\n', ''))
# check to see if the list length is 15.
if len(words) == 15:
# join all words in list separated by a space
# put a . at the end
# add new line
sent.write("{}.\n".format(" ".join(words)))
# or without a .
# sent.write("{}\n".format(" ".join(words)))
# empty the list
words = []
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.