正規表現で漢字と数字を同時に除去し、データを出力したいです。
正規表現を使って、「年」と言う単語と数字(例19〜〜〜などの年代を示すもの)を削除しようとしています。
ご教示いただきたい点は、漢字と数字を同時に正規表現で取り除く方法についてです。
試したこと
re.findallを使ってこのようなコードを書きました。
数字を削除することができました。
re.findall('[^0-9]+',new_type)
漢字の部分を除去しようと考え
re.findall('[^年]+',new_type)
として、無事漢字の部分だけの除去をすることができました。
そしてその後これらを合わせたコード。
re.findall('[^0-9]+|[^年]',new_type)
を出力したのですが、元に戻ってしまいました。
or条件だったことに気づき、次のコードに書き換えました。
re.findall('^(?=.*[^年])(?!.*[^0-9]).*$',new_type)
ですが、今度は中身が全て消えてしまいました。
最終的にやりたいこととしては、年という文字と数字の部分のデータを除去したいと考えています。
できれば年号も。。。。。
その後もう一度調べた結果、regexのモジュールを使う方法もチラッとあったのですが最終的には使うしかないのでしょうか?
補足情報(FW/ツールのバージョンなど)
基礎となるコード
def elsepe (): for per in all: for two in all.find_all('tr'): for three in two.find_all('td'): un = three.get_text(strip=True) for more in three.select('a'): new_type = more.get_text(strip=True) #下記のコードの書き換えを何度もしています。(**の部分) **one = re.findall('[^0-9]+|[^年]+',new_type)** show = print(one) return show elsepe()
発生している問題
一部抜粋です。
このように何もない状況です。
[] [] [] [] [] [] [] [] [] [] [] [] [] []
全体のソースコード
python
1import requests 2import re 3import matplotlib.pyplot as plt 4import numpy as np 5from matplotlib.offsetbox import AnchoredText 6from bs4 import BeautifulSoup 7from requests.exceptions import Timeout 8 9 10 11url = 'https://ja.wikipedia.org/wiki/%E5%86%85%E9%96%A3%E7%B7%8F%E7%90%86%E5%A4%A7%E8%87%A3#%E5%86%85%E9%96%A3%E7%B7%8F%E7%90%86%E5%A4%A7%E8%87%A3%E3%81%AE%E4%B8%80%E8%A6%A7_2' 12try: 13 r = requests.get(url,timeout=3.5) 14except Timeout: 15 print('this is timeout error') 16 pass 17html_soup = BeautifulSoup(r.text,'html.parser') 18 19all = html_soup.find('table',class_='sortable wikitable') 20 21def person_name(): 22 for per in all: 23 for two in all.find_all('tr'): 24 for three in two.find_all('td'): 25 un = three.get_text(strip=True) 26 for more in three.find_all('b'): 27 ni = more.get_text(strip=True) 28 ori = print(ni) 29 30 return ori 31 32def elsepe (): 33 for per in all: 34 for two in all.find_all('tr'): 35 for three in two.find_all('td'): 36 un = three.get_text(strip=True) 37 for more in three.select('a'): 38 new_type = more.get_text(strip=True) 39 one = re.findall('^(?=.*[^年])(?!.*[^0-9]).*$',new_type) 40 show = print(one) 41 return show 42person_name() 43elsepe() 44
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/05/22 13:55