Skip to content

how to parse unbullet list / tree list? #328

Closed

Description

@joycey97

for a section inside an Infobox:

| ethnic_groups          = {{ublist |item_style=white-space:nowrap; |{{Tree list}}
*62.0% [[Singaporean]]
*9.1% [[Permanent residency in Singapore|Permanent resident]]
**71.1% Citizen/resident
*** 74.3% [[Chinese Singaporeans|Chinese]]
*** 13.5% [[Malay Singaporeans|Malay]]
*** 9.0% [[Indian Singaporeans|Indian]]
***3.2% [[Demographics of Singapore#Ethnic groups|Other]]
*28.9% [[Demographics of Singapore#Ethnic groups|Non-citizen/resident]]
{{Tree list/end}}
}}

how to use the package to parse this part to obtain:

62.0% Singaporean
9.1% Permanent resident
71.1% Citizen/resident
74.3% Chinese
13.5% Malay
9.0% Indian
3.2% Other
28.9% Non-citizen/resident

Activity

  1. JJMC89 commented on Aug 22, 2024

    @JJMC89
    import mwparserfromhell
    
    text = """{{infobox
    | ethnic_groups          = {{ublist |item_style=white-space:nowrap; |{{Tree list}}
    *62.0% [[Singaporean]]
    *9.1% [[Permanent residency in Singapore|Permanent resident]]
    **71.1% Citizen/resident
    *** 74.3% [[Chinese Singaporeans|Chinese]]
    *** 13.5% [[Malay Singaporeans|Malay]]
    *** 9.0% [[Indian Singaporeans|Indian]]
    ***3.2% [[Demographics of Singapore#Ethnic groups|Other]]
    *28.9% [[Demographics of Singapore#Ethnic groups|Non-citizen/resident]]
    {{Tree list/end}}
    }}
    }}
    """
    
    wikicode = mwparserfromhell.parse(text)
    infobox_tpl = wikicode.filter_templates()[0]  # select infobox
    ethnic_groups = infobox_tpl.get('ethnic_groups').value  # parameter value of interest
    ubl_tpl = ethnic_groups.filter_templates()[0]  # select {{ublist}}
    ubl_stripped = ubl_tpl.get('1').value.strip_code()  # stripped parameter value of interest
    res = '\n'.join(l.strip() for l in ubl_stripped.splitlines())  # trim leading/trailing whitespace
    
    print(res)
  2. joycey97 commented on Aug 22, 2024

    @joycey97
    Author

    @JJMC89 Thank you. How to list all "keys" (parameter names) from infobox_tpl if there are other fields like

    | ethnic_groups_year     = 2023
    | religion_year          = 2020
    

    in the Infobox?

  3. JJMC89 commented on Aug 22, 2024

    @JJMC89
    param_names = [p.name for p in infobox_tpl.params]
  4. joycey97 commented on Aug 22, 2024

    @joycey97
    Author
    param_names = [p.name for p in infobox_tpl.params]

    Thank you!

  5. Repository owner locked and limited conversation to collaborators on Aug 29, 2024
  6. converted this issue into a discussion #331 on Aug 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions