📜  打印字符串的所有唯一单词

📅  最后修改于: 2022-05-13 01:55:13.680000             🧑  作者: Mango

打印字符串的所有唯一词

编写一个将字符串作为参数并打印其中所有唯一单词的函数。

例子:

Input : Java is great. Grails is also great
Output : Java
         Grails
         also

方法:
这个想法是使用地图来跟踪已经出现的单词。但首先,我们必须从一个字符串中提取所有单词,因为一个字符串可能包含许多带有标点符号的句子。
要从字符串中提取单词,请参阅从字符串中提取每个单词。

Python:这个想法是使用字典来计算每个单词的计数。但首先,我们必须从字符串中提取所有单词,因为字符串可能包含标点符号。这是使用正则表达式或正则表达式完成的。字典中计数为 1 的单词是唯一单词。

Java
// Java program to print unique words
// from a string
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Test
{
    // Prints unique words in a string
    static void printUniquedWords(String str)
    {
        // Extracting words from string
        Pattern p = Pattern.compile("[a-zA-Z]+");
        Matcher m = p.matcher(str);
         
        // Map to store count of a word
        HashMap hm = new HashMap<>();
         
        // if a word found
        while (m.find())
        {
            String word = m.group();
             
            // If this is first occurrence of word
            if(!hm.containsKey(word))
                hm.put(word, 1);
            else
                // increment counter of word
                hm.put(word, hm.get(word) + 1);
             
        }
         
        // Traverse map and print all words whose count
        // is  1
        Set s = hm.keySet();
        Iterator itr = s.iterator();
 
        while(itr.hasNext())
        {
            String w = itr.next();
             
            if (hm.get(w) == 1)
                System.out.println(w);
        }   
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "Java is great. Grails is also great";
        printUniquedWords(str);
    }
}


Python3
# Python program to print unique word
# in a string.
# Using re (Regular Expression module)
# It is used here to match a pattern
# in the given string
import re
 
# Declare a dictionary
dict = {}
 
# Method to check whether the word
# exists in dictionary or not
def uniqueWord(Word):
 
    if Word in dict:
 
        # If the word exists in dictionary then
        # simply increase its count
        dict[words] += 1
 
    else:
 
        # If the word does not exists in
        # dictionary update the dictionary
        # and make its count 1
        dict.update({words: 1})
 
# Driver code
if __name__ == '__main__':
     
    string = "Java is great. Grails is also great"
     
    # re.split() method is used to split
    # all the words in a string separated
    # by non-alphanumeric characters (\W)
    ListOfWords = re.split("[\W]+", string)
 
    # Extract each word from ListOfWords
    # and pass it to the method uniqueWord()
    for words in ListOfWords:
        uniqueWord(words)
 
    # Iterate over dictionary if the value
    # of the key is 1, then print the element
    for elements in dict:
        if dict[elements] == 1:
            print(elements)


Python3
# python program to print all
# the unique words in a string
# in python using set() method
# function to print unique words
 
 
def printWords(l):
     
    # for loop for iterating
    for i in l:
        print(i)
 
 
# Driver code
str = "geeks for geeks"
 
# storing string in the form of list of words
s = set(str.split(" "))
 
# passing list to print words function
printWords(s)


输出:
Java
Grails
also

方法二:使用 set()

方法:

在这种方法中,我们以一组单个单词的形式存储字符串并打印单词。要在这个方法中解决这个问题,首先我们需要了解 https://www.geeksforgeeks.org/sets-in-python/

下面是上述方法的实现:

Python3

# python program to print all
# the unique words in a string
# in python using set() method
# function to print unique words
 
 
def printWords(l):
     
    # for loop for iterating
    for i in l:
        print(i)
 
 
# Driver code
str = "geeks for geeks"
 
# storing string in the form of list of words
s = set(str.split(" "))
 
# passing list to print words function
printWords(s)
输出
geeks
for