I want to do the following but I don’t know how to get the name and percentage:

mymodule_test.py

import unittest

from unittest import TestCase

from mymodule import get_wanted_cards, get_percentage


class GetCardsTestCase(TestCase):
    def test_get_wanted_cards(self):
        s = '''
↑	A Little Chat	92 (1%)	0 (0%)	NEW
↑	An Offer You Can't Refuse	88 (87%)	0 (0%)	NEW
↑	Angelic Observer	92 (91%)	0 (0%)	NEW
'''
        expected = ["4 An Offer You Can't Refuse", "4 Angelic Observer"]
        actual = get_wanted_cards(s)
        self.assertEqual(actual, expected)

    def test_get_percentage(self):
        s = "92 (1%)"
        expected = 1
        actual = get_percentage(s)
        self.assertEqual(actual, expected)


if __name__ == '__main__':
    unittest.main()

mymodule.py

import re

from typing import List


def get_wanted_cards(s: str) -> List[str]:
    res = []
    for line in s.splitlines():
        array = line.split("\t")
        if len(array) < 5:
            continue
        name = array[1]
        percent = get_percentage(array[2])
        if percent >= 50:
            res += "4 " + name
    return res


def get_percentage(s: str) -> int:
    return int(re.match(r'\(([0-9]*)%\)', s).group(1))


if __name__ == "__main__":
    pass
  • thann@heapoverflow.mlM
    link
    fedilink
    arrow-up
    4
    ·
    2 years ago

    It’s hard to understand what you’re trying to do here…
    I would recommend stripping the problem down to a couple lines and explaining what you want and why your code doesn’t work.

    If you’re trying to extract information from a string regular expressions are the way to go. You should probably add more to the regexp to capture the name and the percentage, like so:

    re.match(r'(.*) \(([0-9]*)%\)', s).groups()

    • OptimusPrime@lemmy.mlOP
      link
      fedilink
      arrow-up
      1
      ·
      2 years ago

      I want to get the names and the percentages from the string. I’ve managed to get the percentage by substituting match for search. But I’m still getting an error while getting the name.

      • thann@heapoverflow.mlM
        link
        fedilink
        arrow-up
        3
        ·
        2 years ago

        I see.

        res += "4 " + name The problem here is you’re doing <List> += <str>

        Changing it to: res.append('4 ' + name) fixes it