![](/img/trans.png)
[英]How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python
[英]In Python, how do I parse each word in a text file and make each word lowercase and remove special characters except for apostrophes?
這是我到目前為止的代碼。 它小寫輸入文件中的每個單詞,但我不確定如何檢查和刪除輸入文件中的特殊字符,撇號除外。
input("Please enter a file name: ")
with open(input(), 'r') as input_file:
for line in input_file:
for word in line.split():
word.lower()
您可以使用:
re.sub(ur'[^a-zA-Z0-9]')
似乎您只是在嘗試讀取輸入文件而不是覆蓋它,所以我寫的只是將結果打印出來。
可以使用 Python String isalnum() 方法https://www.w3schools.com/python/ref_string_isalnum.asp
根據文檔:“如果所有字符都是字母數字,則 isalnum() 方法返回 True,表示字母 (az) 和數字 (0-9)。”
假設滿足您的要求,以下應該可以工作。
alphanumeric = ""
with open(r"C:\Users\TestUser\Desktop\test.txt", 'r') as input_file:
for line in input_file:
for c in line:
if c == "'":
alphanumeric += "'"
elif c == " ":
alphanumeric += " "
elif c.isalnum():
alphanumeric += c
print(alphanumeric.lower())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.