是否可以在包含“firstword”的所有行中將“firstword”替換為“BBBBB”?
請問,我的代碼有什么問題?它會找到我從 most_occur1 中選擇的單詞,并且會盡可能多地列印“found it”這個詞出現的次數(我用它只是為了測驗),但它不會取代它。
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')
uj5u.com熱心網友回復:
我在這里看到的主要內容是您正在拆分文本,然后替換拆分文本串列中的內容,這不會影響原始文本。
像這樣:
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"最終會有。
uj5u.com熱心網友回復:
我希望這段代碼可以幫助您:
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)
與regexB 列中的內容無關。您可以firstword在任何地方替換任何內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/312279.html
標籤:Python 蟒蛇-3.x 擅长 python-2.7
下一篇:熊貓爆炸功能無法正常作業
