python - 如何从文件中的单词列表创建句子
问题描述
我有一个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 = []
我希望这有帮助。
推荐阅读
- wpf - 在一个窗口中显示两个 wpf 窗口
- json - 需要过滤值包含特定子字符串的所有键/值对
- android - 将自定义大小设置为自定义 cordova 插件
- java - 有没有办法强制等待 Java 进程结束以在 Scala 或 Spark 中结束?
- python - 加载相关表的所有列 | Flask-SqlAlchemy
- string - 如何在python2中对不同类型的不同字符串进行操作?
- python - IPython autoreload 如何知道函数已更改?
- python - 如何使用pandas melt 将多列转换为行
- laravel - 如何在使用 Laravel access_token 时修复“此令牌未签名”
- c++ - 跳跃二分搜索有直观的解释吗?