LoginSignup
15698-sai
@15698-sai (開基 斎藤)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

bs4での文字列検索

解決したいこと

passageの中のabstractのテキストにfirstまたはsecondが含まれていたら、textを返すプログラムなんですが、このor条件をadd条件にしたいのですが分からなかったので教えて頂きたいです.

該当するソースコード


    for body in file_read_generator('1.xml', '<document>', '</document>'):
    
        soup = BeautifulSoup(body,features= "lxml")
        texts = soup.select(f'''
            passage >
                infon[key="type"]:-soup-contains("abstract") ~ text:-soup-contains("first","second") 
            ''')
        text=[]
        for t in texts:
            text.append(t.text)
0

1Answer

Add条件……And…ですかね……?
そうであれば多分これでいけます。

-            passage >
-                infon[key="type"]:-soup-contains("abstract") ~ text:-soup-contains("first","second") 
+            passage >
+                infon[key="type"]:-soup-contains("abstract") ~ text:-soup-contains("first"):-soup-contains("second")

BeautifulSoupのクエリっぽいものも、:-soup-contains(文字列)のような独特な記法を含むものの、CSSセレクタをベースにしているようです。
ならばと、CSSセレクタの原則に従い、追加で絞る為の条件はスペースを挟まず追記するようにしたところ……なんかいけました。

1

Your answer might help someone💌