![](/img/trans.png)
[英]how to change colour of specific words in a powerpoint in python
[英]How to readline and access to specific words and change word on the samefile on Python
首先,我試圖找到 "ifrs_Revenue" 並更改位於"ifrs_Revenue"
旁邊的單詞,但它失敗了。
f = open(input_path +'/CIS' + "/16_1분기보고서_03_포괄손익계산서_연결_2212.txt")
while line:
if "ifrs_Revenue" in line:
s_line = line.split("\t")
idx = s_line.index("ifrs_Revenue")
value = s_line[idx+1]
value = value.replace(value,'매출액')
break
line = f.readline()
然后,我找到了另一種方法來一次替換同一文件中的特定單詞。
def inplace_change(filename, old_string, new_string):
with open(filename) as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
with open(filename, 'w') as f:
print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
s = s.replace(old_string, new_string)
f.write(s)
b_list = os.listdir(input_path +'/CIS')
for blist in b_list:
for old, new in zip([' 지배기업의 소유주에게 귀속되는 당기순이익(손실)','수익(매출액)', '영업수익', '영업이익(손실)', '관리비및판매비', '영업관리비용(수익)',' 지배기업의 소유주지분' ],['당기순이익(지배)', '매출액', '매출액','영업이익', '판매비와관리비', '판매비와관리비','당기순이익(지배)' ]):
inplace_change(input_path +'/CIS'+ '/' + blist, old_string= old, new_string= new)
break
我想要的是統一更改特定單詞旁邊的單詞,但是無論我如何搜索,我都找不到方法,所以我來到了這里。 我是一個不會說英語的居民,所以我請求您使用翻譯的理解。
我附上一張圖片以幫助您理解。 非英語單詞是韓語:圖片
我制作了一個簡單的示例文件來模擬您正在使用的數據,所有數據都由制表符(“\t”)分隔:
col1 col2 col3
randomwords ifrs_Revenue replaceme
morerandomwords ifrs_CostOfSales this_should_stay_the_same
asdfasdfasdf ifrs_Revenue alsoreplaceme
jajajajajaja ifrsGrossProfit this_should_not_be_replaced
然后我使用 pandas 模塊搜索並找到“col2”==“ifrs_Revenue”的所有位置。 在您的情況下,您將用列的名稱替換“col2”。 “col3”也是如此,您想將其替換為您要替換的列名。 代碼如下:
import pandas as pd
df = pd.read_csv("example.txt", sep="\t") # read in data
# NOTE: make sure to replace "example.txt" with your own filename
print(df.head())
mask = df.col2 == "ifrs_Revenue" # create mask that finds all rows with "ifrs_Revenue"
df.loc[mask, "col3"] = "REPLACED_VALUE" # "REPLACED_VALUE" will be the valie you want to use to replace
# also replace "col3" with the column you are replacing
print("=" * 50)
print(df.head())
df.to_csv("results.tsv", sep="\t") # this saves the results, change "results.tsv" to be whatever you want the save to be
這些是結果:
col1 col2 col3
0 randomwords ifrs_Revenue REPLACED_VALUE
1 morerandomwords ifrs_CostOfSales this_should_stay_the_same
2 asdfasdfasdf ifrs_Revenue REPLACED_VALUE
3 jajajajajaja ifrsGrossProfit this_should_not_be_replaced
如果您需要任何澄清,請告訴我!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.