首页 > 解决方案 > 如何从文件中的单词列表创建句子

问题描述

我有一个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)

标签: python

解决方案


如果您的 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 = []

我希望这有帮助。


推荐阅读