Home > Back-end >  Can I exclude lines starting with #?
Can I exclude lines starting with #?

Time:10-28

Line 4 counts number of lines from response. Trying to exclude lines that start with # from the count.Possible?

def fetch_blocklist_count(session: requests.Session, url: str, timeout: int) -> BlocklistResponse:
    try:
        with session.get(url, timeout=timeout) as response:
            dooct = {url: len(response.text.splitlines())}
            return dooct
    except requests.exceptions.RequestException as e:
        return 'booger'


def test_count(timeout: int=10):
    session = requests.Session()
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = []
        block_host = utils.build_source_list()
        for blocklist in block_host:
            if not blocklist.startswith('#'):
                futures.append(executor.submit(fetch_blocklist_count, session, blocklist, timeout))
        results = [future.result() for future in concurrent.futures.as_completed(futures)]
    return results

CodePudding user response:

You can trivially use list comprehensions for what you are trying to do:

Use len([l for l in response.text.splitlines() if len(l)<1 or l[0] != '#'])

CodePudding user response:

You could exclude the lines that start with "#" by applying a filter to a list comprehension as follows:

dooct = {
    url: len(
        [
            line for line in response.text.splitlines()
            if line and not line.startswith("#")
        ]
    )
}

Notice that line and not line.startswith("#") will be True if and only if line is not "" and the line does not start with "#".

  • Related