简体   繁体   中英

python else statement syntax error

when I run this, I get the following error: Does anybody know what might be causing this? The purpose of this program is to create an array, remove all punctuation from the array, and remove all lowercase characters from the array

File "words.py", line 37 else: ^ SyntaxError: invalid syntax

shell returned 1

import sys
from scanner import *
arr=[]
def main():
    print("the name of the program is",sys.argv[0])
    for i in range(1,len(sys.argv),1):
        print("   argument",i,"is", sys.argv[i])
    tokens = readTokens("text.txt")
    cleanTokens = depunctuateTokens(arr)
    words = decapitalizeTokens(result)


def readTokens(s):
    s=Scanner("text.txt")
    token=s.readtoken()
    while (token != ""):
        arr.append(token)
        token=s.readtoken()
    s.close()
    return arr

def depunctuateTokens(arr):
    result=[]
    for i in range(0,len(arr),1):
        string=arr[i]
        cleaned=""
        punctuation="""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
        for i in range(0,len(string),1):
            if string[i] not in punctuation:
                cleaned += string[i]
        result.append(cleaned)
    print(result)
    return result


def decapitalizeTokens(result):
    if (ord(result) <= ord('Z')):
        return chr(ord(result) + ord('a') - (ord('A'))
    else:
        return result

main()

Edit:

You are already returning result from depunctuateTokens , so just do this inside main :

cleanTokens = depunctuateTokens(arr)
words = decapitalizeTokens(cleanTokens)


You need a closing parenthesis:

return chr(ord(result) + ord('a') - (ord('A'))
#                                       here--^

Or, you can remove the extra opening parenthesis:

return chr(ord(result) + ord('a') - (ord('A'))
#                             here--^

Personally, I would recommend the later solution. You should only use parenthesis if:

  1. The syntax requires you to.

  2. It will noticeably improve the clarity of the code.

Otherwise, they are just redundant characters.

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