Python 将文本中的单词替换为其他文件中包含的单词';s列
我试图用大文本中另一列中的其他单词替换一列中的单词 数据: 桌子和椅子都坏了 孩子们在街上玩 我有很多猫 文本列 缩写,缩写 桌子,桌子 椅子,椅子 是,是 输,输 断了,断了 孩子,孩子们 玩,玩 猫,猫 月光 输出良好:Python 将文本中的单词替换为其他文件中包含的单词';s列,python,python-3.x,csv,Python,Python 3.x,Csv,我试图用大文本中另一列中的其他单词替换一列中的单词 数据: 桌子和椅子都坏了 孩子们在街上玩 我有很多猫 文本列 缩写,缩写 桌子,桌子 椅子,椅子 是,是 输,输 断了,断了 孩子,孩子们 玩,玩 猫,猫 月光 输出良好: import csv with open('data.csv', 'r') as file, open('text-columns.csv', 'r') as columns: text_csv = csv.reader(columns, delimiter =
import csv
with open('data.csv', 'r') as file, open('text-columns.csv', 'r') as columns:
text_csv = csv.reader(columns, delimiter = ',')
text_csv = list(text_csv)
res = []
for row in file:
if row:
for checkVal in text_csv:
if checkVal[1] in row:
row = row.replace(checkVal[1], checkVal[0])
res.append(row)
with open("out.csv", 'w') as file:
for row in res:
file.write(row)
桌子和椅子被打破
孩子在街上玩耍
我有很多猫
我的输出:
回溯(最近一次呼叫最后一次):
文件“l.py”,第15行,在
新建文本=新建行。替换(元素[1],元素[0])
索引器错误:字符串索引超出范围
这是一种方法
Ex:
import csv
with open('data.csv', 'r') as file, open('text-columns.csv', 'r') as columns:
text_csv = csv.reader(columns, delimiter = ',')
text_csv = list(text_csv)
res = []
for row in file:
if row:
for checkVal in text_csv:
if checkVal[1] in row:
row = row.replace(checkVal[1], checkVal[0])
res.append(row)
with open("out.csv", 'w') as file:
for row in res:
file.write(row)
new_rows=','.join(逐字逐行)
不会做您认为它会做的事情word
不是你想象的那样。打印出来,你会看到的。谢谢,但不起作用。我也有同样的问题:-(**输出:**表AHA chber被破坏ChewillohHave在街上被使用我有很多猫。对于给定的示例,它工作得很好。你能提供一个不起作用的示例内容以便我可以测试吗?谢谢,但这里不起作用:(输出第一句话:表AHA让chber被打破第二句话:Chewillohhave在街上上路第三句话:我有很多猫。它只需要几个词就行了,但是其他的都很奇怪。谢谢你的帮助。