【问题标题】:How to replace words in excel file using python如何使用python替换excel文件中的单词
【发布时间】: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


【解决方案1】:

我在这里看到的主要内容是您正在拆分文本,然后替换拆分文本列表中的内容,这不会影响原始文本。

就像这样:

text = "one, two, three, four, things"
for x in text.split(", "):
    x.replace("o", "q")

不会更改变量text。它只是更改列表["one", "two", "three", "four", "things"] 中生成的元素,以便在for 中使用。

不确定仅此一项是否足以为您指明正确的方向。

一种解决方法是:

text = "one, two, three, four, things"

new_text = []
for x in text.split(", "):
    x.replace("o", "q")
    new_text.append(x)

text = ", ".join(new_text)

那么你最后会得到"qne, twq, three, fqur, things"

【讨论】:

  • 已经尝试过了,但它不会修改我的excel文件中的任何内容
  • 我仍然认为这是因为您没有将更改后的内容写回文件中。不过,我不确定写入 excel 文件的正确方法是什么,因为我从未使用过这些文件。但我很确定问题在于您只是在更改复制的版本(您从 excel 文件中获得的文本)而不是原始文件本身。
【解决方案2】:

希望这段代码对你有帮助:

from typing import Counter
import pandas as pd
import re

df = pd.read_excel (r'yourexcelfilename.xlsx', engine='openpyxl', header=None)

most_occur = Counter(df[1]).most_common(40)

print (most_occur)

firstword = input('Please type word from list:  ')
print('this is: ' + firstword)
print('Replacing '+ firstword+' with bbbbbbb')

for row in df[1].index:
    df.loc[row, 1] = re.sub(firstword,"bbbbbbb", df.loc[row,1] )
print(df)

regex 与 B 列中的内容无关。您可以将 firstword 替换为任何地方的任何内容。

【讨论】:

  • 您好,谢谢。这将不起作用,主要是因为我使用的代码从 1-2000 范围内获取每个单元格,并在一个单元格内拆分单词(来自 B 单元格的值包含由多个单词组成的名称)。此建议计算完整的单元格
  • 如果这个答案的唯一问题是 df.loc[name][1] 是一个完整的单元格(...但是你需要替换其中的单词),你可以试试这个 df.loc[name, 1] = " ".join([“bbbbbbb” if word == firstword else word for word in df.loc[name][1].split()]) 而不是两个你在 for 循环中的行(我猜你在单元格中的单词是用空格分隔的)。
  • @madacmjtr 在 for 循环中的数据数不是问题。如果您想迭代特定数量的数据,请根据需要修改代码。我稍微改了一下代码,看看吧
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 2022-11-19
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多