Python実践:文字処理とコンテナの応用

1. 5または6で割り切れるが、両方で割り切れない数の抽出

def find_divisible_numbers(limit=10000):
    result = []
    for num in range(1, limit + 1):
        if (num % 5 == 0 or num % 6 == 0) and num % 30 != 0:
            result.append(num)
    return result

print(find_divisible_numbers())

2. リストの偶数インデックス要素の合計計算

def compute_even_indices_sum(data):
    total = 0
    for idx in range(0, len(data), 2):
        total += data[idx]
    return total

sample_data = [4, 6, 9, 5, 78, 152, 32, 45, 8, 54, 12, 16, 18]
print(compute_even_indices_sum(sample_data))

3. ファイルパスの要素分解

import os

path = "/home/user/docs/report.txt"
dir_path, file_name = os.path.split(path)
base_name, ext = os.path.splitext(file_name)

print(f"ディレクトリ: {dir_path}")
print(f"ファイル名: {base_name}")
print(f"拡張子: {ext}")

4. 文字列の句読点で分割

import re

def split_by_punctuation(text):
    segments = re.split(r'([.,!?;])', text)
    return ''.join([seg + '\n' if seg in ',.!?;' else seg for seg in segments]).rstrip('\n')

print(split_by_punctuation("こんにちは、世界!これはテストです。"))

5. 文字列配列の空白除去

text_list = ["  apple", "banana ", " orange "]
cleaned = [item.strip() for item in text_list]
print(cleaned)

6. ゲーム名の一致判定(大文字小文字無視)

def compare_game_titles(title1, title2):
    return title1.lower() == title2.lower()

print(compare_game_titles("Lol", "LOL"))

7. 日期フォーマット変換

from datetime import datetime

def format_date(input_date):
    y, m, d = input_date.split('/')
    return f"{y}年-{int(m)}月-{int(d)}日"

print(format_date("2023/09/15"))

8. 文字列の並べ替えと逆順出力

def reverse_sorted_string(s):
    sorted_chars = sorted(s)
    return ''.join(sorted_chars[::-1])

print(reverse_sorted_string("cabed"))

9. 文字列の単語を逆順に並べ替え

def reverse_word_order(sentence):
    words = sentence.split()
    return ' '.join(words[::-1])

print(reverse_word_order("hello c java python"))

10. URLからユーザー名とドメイン抽出

from urllib.parse import urlparse, parse_qs

url = "https://example.com?user=admin&password=123"
parsed = urlparse(url)
query_params = parse_qs(parsed.query)

print(f"ドメイン: {parsed.netloc}")
print(f"ユーザー名: {query_params.get('user', [''])[0]}")

11. 書名の長さ処理

book_titles = ["Python入門", "データ構造の基礎", "AI開発の実践", "超短いタイトル"]
formatted_titles = []
for title in book_titles:
    if len(title) > 8:
        formatted_titles.append(f"{title[:8]}...")
    else:
        formatted_titles.append(title)
print(formatted_titles)

12. 特定文字の位置検索

def find_occurrences(text, char='呵'):
    return [i for i, c in enumerate(text) if c == char]

print(find_occurrences("こんにちは呵、テスト呵"))

13. 文字列の特定文字の置換

def censor_text(text, target="邪恶", replacement="**"):
    return text.replace(target, replacement)

print(censor_text("老牛はとても邪悪です"))

14. パリンドローム判定

def is_palindrome_check(s):
    return s == s[::-1]

print(is_palindrome_check("123454321"))
print(is_palindrome_check("上海自来水来自海上"))

15. ファイルフィルタリング

import os

def find_python_files(directory):
    return [f for f in os.listdir(directory) if f.endswith('.py') and 'xx' in f]

print(find_python_files("/path/to/directory"))

タグ: Python string processing regular expression file handling URL parsing

6月21日 18:51 投稿