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
439 views
in Technique[技术] by (71.8m points)

python - 如何在字符串中搜索没有空格的单词(How to I search a string for words with no spaces)

I am trying to find out how to read a string for names with no spaces ex.

(我正在尝试找出如何读取不带空格的名字的字符串。)

robbybobby I want it to search the string and separate them into there own groups

(robbybobby我希望它搜索字符串并将它们分成自己的组)

def wordcount(filename, listwords):
    try:
        file = open(filename, "r")
        read = file.readline()
        file.close()
        for word in listwords:
            lower = word.lower()
            count = 0
            for letter in read:
                line = letter.split()
                for each in line:
                    line2 = each.lower()
                    line2 = line2.strip(".")
                    if lower == line2:
                        count += 1

            print(lower, ":", count)
    except FileExistsError:
        print("no")
wordcount("teststring.txt", ["robby"])

with this code it will only find robby if there is a space afterwards

(使用此代码,只有在以后有空格的情况下,它才会发现robby)

  ask by Xtyfi translate from so

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

1 Reply

0 votes
by (71.8m points)

There are several ways to do this.

(有几种方法可以做到这一点。)

I am posting 2 suggestions so you can understand and improve :)

(我发布2条建议,以便您可以理解和改进:))

Solution 1:

(解决方案1:)

def count_occurrences(line, word):
    # Normalize vars
    word = word.lower()
    line = line.lower()

    # Initialize vars
    start_index = 0
    total_count = 0
    word_len = len(word)

    # Count ignoring empty spaces
    while start_index >= 0:
        # Ignore if not found
        if word not in line[start_index:]:
            break

        # Search for the word starting from <start_index> index
        start_index = line.index(word, start_index)

        # Increment if found
        if start_index >= 0:
            start_index += word_len
            total_count += 1    

    # Return total occurrences
    return total_count

print(count_occurrences('stackoverflow overflow overflowABC over', 'overflow'))

Output: 3

(输出3)

Solution 2:

(解决方案2:)

If you want to go for a regex, this links may be usefull:

(如果您想使用正则表达式,此链接可能会有用:)

  1. Count the occurrence of a word in a txt file in python

    (计算python中txt文件中单词的出现)

  2. Exact match for words

    (单词完全匹配)


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

...