pythonspintax

TypeError: expected string or buffer


Found the code below on Black Hat World Forum, but when i execute it i got this error:

print spin(text) 
 File "C:\Users\test.py", line 30, in spin 
text, n = r.subn(_select, text) 
TypeError: expected string or buffer

Code:

text1 = open("C:\Users\spintaxtext.txt", "r")
text= text1.readlines()    
def get_random(arr):
    return arr[random.randrange(0,len(arr))]

def _select(m):
    choices = m.group(1).split('|')
    return choices[random.randint(0, len(choices)-1)]


def spin(text, tokens=None):
    r = re.compile('{([^{}]*)}')
    while True:
        text, n = r.subn(_select, text)
        if n == 0: break
    if tokens:
        text = multi_replace(text, tokens)
    return text.strip()

def multi_spin(text, tokens=None, delimiter= '\n'):
    lines = text.strip().split(delimiter)
    line = get_random(lines)
    return spin(line, tokens)


def multi_replace(text, dic):
    pattern = "|".join(map(re.escape,dic.keys()))
    return re.sub(pattern,lambda m: dic[m.group()],text)

I am not a coder, can someone help me to figure where is the problem? Thank you


Solution

  • Change:

    text= text1.readlines()
    

    to:

    text = text1.read()
    

    Explanation:

    re.subn(pattern, repl, string, count=0, flags=0)
    

    You are passing a list for string here.