PYTHON如何计算没有特殊字符的单词中的字母

时间:2015-10-23 14:31:20

标签: python file-io

我有一个代码,用于计算最后排除特殊字符的单词中的字母。我只是想办法让它在开头排除特殊字符。

到目前为止我的代码:

inFile = open( 'p.txt', "r" ).readlines()

myResults = []
for i in range( 20 ):
   myResults.append( 0 )

mySpecialList = [ '-', '+', '#', '@', '!', '(', ')', '?', '.', ',', ':', ';', '"', "'", '`' ]

for line in inFile:
   words = str.split( line )
   for word in words:
      if word not in mySpecialList:
         if word[ -1 ] not in mySpecialList :
            myResults[ len( word ) ] += 1
         else :
            myResults[ len( word ) - 1 ] += 1


print( myResults )

3 个答案:

答案 0 :(得分:2)

这是一些简单的代码来计算单个单词的所有字母数字字母。

word = "Hello World!"
count = 0
for c in word:
   if c.isalnum():
      count +1 
print( count )

如果您想使用特殊字符,可以使代码看起来像

    mySpecialList = ['*', '!']
    word = "Hello World!"
    count = 0
    for c in word:
       if c not in mySpecialList:
          count +1 
    print( count )

答案 1 :(得分:0)

你可以使用正则表达式,试一试! 例如,你可以分割字符串,在findall之后你有一个包含所有单词的列表。

import re

string = "Hello World, Hi + Say"
print(re.findall(r"[\w']+", string))

答案 2 :(得分:0)

def reverseword(user_input):
    words=str(user_input).split(" ")
    newWords = [word[::-1] for word in words] 
    newSentence = " ".join(newWords) 
    return newSentence
if __name__ == "__main__":
    while True:
        ispresent=0
        splcharlist=['-', '+', '#', '@', '!', '(', ')', '?', '.', ',', ':', ';', '"', "'", '`'," "]
        user_input=input("Enter the input:")
        print(len(user_input))
        ccount=0
        new_input=""
        ch_count=0
        if len(user_input)>100:
            for eletter in user_input:
                if eletter not in splcharlist:
                    ccount=ccount+1
                ch_count=ch_count+1 
                if ccount>100:
                    break

            new_input=user_input[:100]  
        else:
            new_input=user_input


        print("This is for your input:",user_input)
        print("input with limit :"+str(new_input))
        print(len(new_input))

        print("The Reverse lists is: ",reverseword(new_input))

        if "stop" in user_input:
            break