logo
down
shadow

Is there a way of getting this string down to 3 words?


Is there a way of getting this string down to 3 words?

By : user3042571
Date : November 28 2020, 12:01 PM
I wish this helpful for you The first issue with your code is input = input(). The problem with this is that input is the name of the function you are calling, but you are overwriting input with the user's string. Consequently, if you tried to run input() again, it would fail.
The second issue is that you are misunderstanding lists. In the code below, tokens is a list, not a string. Each element in the list is a string. So there is no need to strip out brackets and such. You can simply order the list (that part of your code was correct) in reverse order of length, then print the first three words.
code :
import re

user_input = input(" ")
prohibited = {'this','although','and','as','because','but','even if','he','and','however','cosmos','an','a','is','what','question :','question','[',']',',','cosmo',' ','  ','   '}
tokens = [word for word in re.split("\W+", user_input) if word.lower() not in prohibited]
tokens.sort(key=len, reverse=True)

print(tokens[0], end=', ')
print(tokens[1], end=', ')
print(tokens[2])
i like eating cake
eating, like, cake


Share : facebook icon twitter icon
How do I check a string for certain words without getting matches for parts of the words in the string in Python?

How do I check a string for certain words without getting matches for parts of the words in the string in Python?


By : Ravikumar P
Date : March 29 2020, 07:55 AM
wish of those help One way to accomplish this would be to split your string into a list, then check if each word is in the list:
code :
string_list = string.split(' ')
for word in wordList:
    if word in string_list:
        print word
for word in wordList:
    posMatch = re.search(r'\b%s\b' % word, string)
    if posMatch:
        print (posMatch.group())
How to match words in 2 list against another string of words without sub-string matching in Python?

How to match words in 2 list against another string of words without sub-string matching in Python?


By : DizzyKnight
Date : March 29 2020, 07:55 AM
this one helps. Store slangNames and riskNames as sets, split the strings and check if any of the words appear in both sets
code :
slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"])
riskNames = set(["enough", "pop", "final", "stress", "trade"])
d =  {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"}

for k,v in d.items():
    spl = v.split() # split once
    if any(word in slangNames for word in spl) and any(word  in riskNames for word in spl):
        print(k,v)
1 Vikes is not enough for me
3 pop a D
slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"])
riskNames = set(["enough", "pop", "final", "stress", "trade"])
d =  {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"}

for k,v in d.items():
    spl = v.split()
    if not slangNames.isdisjoint(spl) and not riskNames.isdisjoint(spl):
        print(k, v)
import re
slangNames = set(["Vikes", "Demmies", "D"])
r = re.compile(r"\bMS Contin\b")
riskNames = set(["enough", "pop", "final", "stress", "trade"])
d =  {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"}

for k,v in d.items():
    spl = v.split()
    if (not slangNames.isdisjoint(spl) or r.search(v)) and not riskNames.isdisjoint(spl):
        print(k,v)
Take a String with any number of words and store the words in different string variables?

Take a String with any number of words and store the words in different string variables?


By : linklux
Date : March 29 2020, 07:55 AM
this one helps. Since you're already using the standard library, why not use a vector?
code :
#include <iostream>
#include <sstream>
#include <vector>
#include <string>

std::string input = "abc def ghi";
std::istringstream ss(input);
std::string token;
std::vector<std::string> vec;

while(std::getline(ss, token, ' ')) {
    vec.push_back(token);
}  
//vec now contains ['abc', 'def', 'ghi']
How to compare words of one string in Java with words of another string and separate the words on match?

How to compare words of one string in Java with words of another string and separate the words on match?


By : petrt88
Date : March 29 2020, 07:55 AM
it should still fix some issue The issue you're having (and the reason the first string succeeded and the second does not) is to do with the order of words in the dict. Your current implementation checks if the words in the dict appear in the string exactly in the order they were entered into the dict - after you found the first word, put in a space and proceed to find the second word. If you did not find the next word, you do not proceed with the process.
There are many ways to rewrite the code to get what you want, but the minimal change is:
code :
public class Sample1 {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
int i,j,k,len;
    String[] dict= {"how","are","you","something","needs","to","be","done"};
    //StringBuilder str=new StringBuilder("howareyou");
    StringBuilder str=new StringBuilder("somethingneedstobedone");
    len=str.length();
    for(i=0,j=0;i<len;i++) //removed k from here
    {
        for(j=i+1;j<len;j++)
        {
          for (k=0;k<dict.length;k++) { //added this loop!
            if(dict[k].toString().equals(str.substring(i, j)))
            {
                str.insert(j, " ");
            }
          } //Loop closing for k - the dictionary
        }
    }
    System.out.println(str); 
    sc.close();
}
How to compare string with array of words and highlight words in string that match?

How to compare string with array of words and highlight words in string that match?


By : Gazeld
Date : March 29 2020, 07:55 AM
it should still fix some issue Convert the array to a regular expression, and use String#Replace to wrap the words with a span:
code :
const words = ['prueba', 'etiquetas'];
const product = 'Prueba Pruebaa de etiquetas aetiquetas';

// convert the array to a regular expression that looks for any word that is found in the list, regardless of case (i), over all the string (g)
const regexp = new RegExp(`\\b(${words.join('|')})\\b`, 'gi');

// replace the found words with a span that contains each word
const html = product.replace(regexp, '<span class="highlight">$&</span>');

demo.innerHTML = html;
.highlight {
  background: yellow;
}
<div id="demo"></div>
Related Posts Related Posts :
  • Tuning the hyperparameter with gridsearch results in overfitting
  • some coordinates that I extracted from geocoder in Python are not saving in the variable I created
  • 7C in cs circles- python Im not sure what is wrong with this yet
  • How to fix 'AttributeError: 'list' object has no attribute 'shape'' error in python with Tensorflow / Keras when loading
  • python - thread`s target is a method of an object
  • Retrieve Variable From Class
  • What is the reason for matplotlib for printing labels multiple times?
  • Why would people use ThreadPoolExecutor instead of direct function call?
  • When clear_widgets is called, it doesnt remove screens in ScreenManager
  • Python can't import function
  • Pieces doesn't stack after one loop on my connect4
  • How to change font size of all .docx document with python-docx
  • How to store a word with # in .cfg file
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org