简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM