Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

python - How to separate comma from word (tokenization)

I have some problem with tokenization, the assignment is to separate a sentence into words.

This is what I have done at the moment.

def tokenize(s):

    d = []
    start = 0
    
    while start < len(s):
        while start < len(s) and s[start].isspace():
            start = start+1

        end = start
        while end < len(s) and not s[end].isspace():
            end = end+1

        d = d + [s[start:end]]
        start = end
            
    print(d)

Running the program:

>>> tokenize("He was walking, it was fun")
['He', 'was', 'walking,', 'it', 'was', 'fun']

This works fine, but the problem is as you can see that my program will include the comma in the word walking. I want to separate the comma (and other "symbols") as an individual "word".

Such as:

['He', 'was', 'walking', ',', 'it', 'was', 'fun']

How can I modify my code to fix this?

Thanks in advance!

question from:https://stackoverflow.com/questions/65941369/how-to-separate-comma-from-word-tokenization

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a possible suggestion for a modification which will work with your specific example but which will definitely fail with examples like "How are you?!":

def tokenize(s):

    d = []
    start = 0
    
    while start < len(s):
        while start < len(s) and s[start].isspace():
            start = start+1

        end = start
        while end < len(s) and not s[end].isspace():
            end = end+1

        if(s[end-1] in ["!", ",", ".", ";", ":"]):
            d = d + [s[start:(end-1)]]
            d = d + [s[end-1]]
        else:
            d = d + [s[start:end]]
        
        start = end


            
    print(d)

tokenize("He was walking, it was fun!")
# ['He', 'was', 'walking', ',', 'it', 'was', 'fun', '!']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...