はじまり
リサちゃん
今回は、Pythonスクリプトファイルから、関数およびメソッドを全て取得する処理を作るぞ〜。
テストコードとかREADMEを書く時に使ってみたりするぞ〜。
今回のソース
今回のソースはこちらになります。読み取り先ファイルと読み取り元ファイルを同じディレクトリに配置して、この読み取り元ファイル.pyを実行します。
get_words_in_lines_by_head_and_tail()
で、"def "
と"("
の間の文字列を取得します。
そして、remove_head_spaces()
で、取得した文字列の"def "
より前にある空白文字を削除します。
a
読み取り元ファイル.py
def remove_head_sapces(word : str, spaces : list = [" ", " "]) -> str:
word_removed_space = ""
if len(word) == 0:
word_removed_space = word
elif word[0] in spaces:
word_removed_space = word[1:len(word)+1]
# invisible head character if head space is nothing
print("'{}'".format(word_removed_space[1:len(word)]))
word_removed_space = remove_head_sapces(word_removed_space, spaces)
else:
word_removed_space = word
return word_removed_space
def get_words_in_lines_by_head_and_tail(text_lines : list, head_of_target : str, tail_of_target : str) -> list:
words = []
text_line_removed_head_space = ""
print(text_lines)
for text_line in text_lines:
text_line_removed_head_space = remove_head_sapces(text_line)
head_index = text_line_removed_head_space.find(head_of_target, 0)
if head_index != 0:
continue
tail_index = text_line_removed_head_space.find(tail_of_target, 0+head_index)
if text_line_removed_head_space.find(tail_of_target, 0) == -1:
continue
word = text_line_removed_head_space[len(head_of_target):tail_index]
words.append(word)
return words
def get_functions_in_python_file(file_full_name : str, head_of_function : str = "def ", tail_of_function : str = "(") -> list:
functions = []
text = ""
with open(file_full_name, "r", encoding="UTF-8") as f:
text = f.read()
text_lines = text.split("\n")
functions = get_words_in_lines_by_head_and_tail(text_lines, head_of_function, tail_of_function)
return functions
file_full_name = "読み取り先ファイル.py"
actual = get_functions_in_python_file(file_full_name)
print(actual)
a
読み取り先ファイル.py
class ReplaceCharacter:
def make_voicedsound(self, text : str) -> str:
pass
def main():
replace_character = ReplaceCharacter()
if __name__ == "__main__":
main()
出力
' def make_voicedsound(self, text : str) -> str:'
' def make_voicedsound(self, text : str) -> str:'
'def make_voicedsound(self, text : str) -> str:'
'ef make_voicedsound(self, text : str) -> str:'
' pass'
' pass'
' pass'
' pass'
' pass'
' pass'
'pass'
'ass'
' replace_character = ReplaceCharacter()'
' replace_character = ReplaceCharacter()'
'replace_character = ReplaceCharacter()'
'eplace_character = ReplaceCharacter()'
' main()'
' main()'
'main()'
'ain()'
['make_voicedsound', 'main']
おしまい
リサちゃん
やったあ、できたあ!
以上になります!
コメント