
我正在尋找一個自訂終端功能change_case
,其功能如下,以幫助我管理網站上的標題:
change_case [option] "string"
option:
upper - STRING TO UPPERCASE
lower - string to lowercase
sentence - Uppercase first letter of every word, others to lowercase
custom - String to Sentence Case except These Words if they appear as the 1st letter:
[in,by,with,of,a,to,is,and,the]
範例標題 -如何讓登入畫面出現而不是自動登入?
上:如何讓登入畫面出現而不是自動登入?
降低:如何讓登入畫面出現而不是自動登入?
句子:如何讓登入畫面出現而不是自動登入?
風俗:如何讓登入畫面出現而不是自動登入?
答案1
這並不太複雜:
- 將下面的腳本複製到一個空檔案中,將其另存為
change_case
(無副檔名)中~/bin
(您可能必須建立目錄)。使腳本可執行 - 您可能必須登出/登錄,特別是如果該目錄尚不存在(或執行
source ~/.profile
:) 打開終端機窗口,透過執行以下命令進行測試:
change_case custom this is a test case to see if all in the script works
輸出:
This is a Test Case to See If All in the Script Works
我用你問題中的所有選項(上、下、句子、自訂)對其進行了測試,所有選項都應該作為你的範例。
劇本
#!/usr/bin/env python3
import sys
string = sys.argv[2:]
opt = sys.argv[1]
excluded = ["in","by","with","of","a","to","is","and","the"]
if opt == "lower":
print((" ").join(string).lower())
elif opt == "upper":
print((" ").join(string).upper())
elif opt == "sentence":
print((" ").join(string).title())
elif opt == "custom":
line = []
for s in string:
s = s.title() if not s in excluded else s
line.append(s)
print((" ").join(line))