【发布时间】:2021-10-01 07:29:59
【问题描述】:
是否可以在包含“firstword”的所有行中将“firstword”替换为“BBBBB”?
请问,我的代码有什么问题?
它会找到我从 most_occur1 中选择的词,并会在该词出现时多次打印“找到它”(我只是为了测试而使用它),但它不会替换它。
def finds_firts_word():
# find first word
for cell in range(1, 2000):
data = sheet.cell(row=cell, column=2).value
if data is not None:
data=data.lower()
data_no_pct = data.translate(str.maketrans('', '', string.punctuation))
big_data1.append(data_no_pct)
x1 = " ".join(big_data1)
split_it1 = x1.split()
Count1 = Counter(split_it1)
most_occur1 = Count1.most_common(40)
print(most_occur1)
firstword = input('Please type word from list: ')
print('this is: ' + firstword)
print('Replacing '+ firstword+' with bbbbbbb')
REPLACE_TXTS = {
firstword: 'BBBBBBBB',
}
for n in split_it1:
if n == firstword:
print('found it')
for search_txt, replace_Txt in REPLACE_TXTS.items():
x = str(split_it1)
x.replace(search_txt, replace_Txt)
print('done')
【问题讨论】:
-
您的代码中不止一处错误。请向我们展示您的一些数据,以便我们重写您的代码。
-
数据很简单:第 1(A) 列包含从 1 到 2000 的行,带有参考编号(eq:x42421 等),第 2(B) 列包含从 1 到 2000 的行,带有项目名称(不同标题)。我知道我是个菜鸟,这段代码到处都是(我是 py 新手),但它做了我需要它做的事情,只是这个替换部分不起作用。
标签: python python-3.x excel python-2.7