我需要在文本檔案中找到所有字串并將其大寫。我已經找到了如何找到字串,但是如果你能幫我列印,我的問題是得到多個字串,給定字串在我的代碼中的位置,非常感謝。
import os
import subprocess
i = 1
string1 = 'biscuit eater'
# opens the text file
# if this is the path where my file resides, f will become an absolute path to it
f = os.path.expanduser("/users/acarroll55277/documents/Notes/new_myfile.txt")
# with this form of open, the wile will automatically close when exiting the code block
txtfile = open (f, 'r')
# print(f.read()) to print the text document in terminal
# this sets variables flag and index to 0
flag = 0
index = 0
# looks through the file line by line
for line in txtfile:
index = 1
#checking if the sting is in the line or not
if string1 in line:
flag = 1
break
# checking condition for sting found or not
if flag == 0:
print('string ' string1 ' not found')
else:
print('string ' string1 ' found in line ' str(index))
uj5u.com熱心網友回復:
我相信你的方法會奏效,但它非常冗長而且不是很 Pythonic。試試這個:
import os, subprocess
string1 = 'biscuit eater'
with open(os.path.expanduser("/users/acarroll55277/documents/Notes/new_myfile.txt"), 'r ') as fptr:
matches = list()
[matches.append(i) for i, line in enumerate(fptr.readlines()) if string1 in line.strip()]
fptr.read().replace(string1, string1.title())
if len(matches) == 0: print(f"string {string1} not found")
[print(f"string {string1} found in line {i}") for i in matches]
現在,這將為檔案中每次出現的字串列印一條訊息。此外,由于該with陳述句,檔案被安全處理并在腳本結束時自動關閉。
uj5u.com熱心網友回復:
您可以使用str.replace-method. 所以在你找到字串的那一行,寫line.replace(string1, string1.upper(), 1). 最后一個1是只使函式替換字串的 1 次出現。
要么,要么您將文本檔案作為字串讀取并replace在整個字串上使用 - 方法。這樣可以省去您手動查找事件的麻煩。在這種情況下,你可以寫
txtfile = open(f, 'r')
content = txtfile.read()
content = content.replace(string1, string1.upper())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/418372.html
標籤:
