Using Google as a Dictionary Lookup via Bash, How Can One Grab The First Definition

Using google as a dictionary lookup via bash, How can one grab the first definition?

This will strip the bullet from the beginning of the first line, printing it and discarding the rest of the output.

sed 's/^ *\* *//; q'

Simplest method to get the dictionary definitions of a list of words in a text file

Although an API or library is probably the way to go (here's some Perl stuff), the Bash script below, which is very rough might give you some ideas:

saveIFS="$IFS"
for w in hello goodbye bicycle world
do
echo
echo "------- $w -------"
def=$(wn $w -over)
IFS=$'\n'
for line in $def
do
echo -e "\t${line}"
IFS="$saveIFS"
if [[ $line =~ ^[[:digit:]]*\. ]]
then
for word in $line
do
echo -e "\t\t${word%*[,;]}"
done
fi
done
IFS="$saveIFS"
done

If you have a list of words in a file, one word to a line, change the first for and last done lines of the script above to:

while read -r w
# . . .
done < wordlist

How to get the first value in a Python dictionary

Try this way:

my_list = [elem[0] for elem in your_dict.values()]

Offtop:
I think you shouldn't use camelcase, it isn't python way

UPD:
inspectorG4dget notes, that result won't be same. It's right. You should use collections.OrderedDict to implement this correctly.

from collections import OrderedDict
my_dict = OrderedDict({'BigMeadow2_U4': (1609.32, 22076.38, 3.98), 'MooseRun': (57813.48, 750187.72, 231.25), 'Hwy14_2': (991.31, 21536.80, 6.47) })

grep/sed/awk paragraphs or sections from lynx output for a dictionary definition

Matching between two lines is possible with sed (https://unix.stackexchange.com/a/264977)

To match between your lines you can pipe to

  sed -n '/^   noun$/,${p;/^$/q}'

This allows your entire script to be tidied to just be

lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}&btnG=Google+Search" | sed -n '/^   '"${2:-noun}"'$/,${p;/^$/q}'

By also using the default parameter syntax in bash (https://coderwall.com/p/s8n9qa/default-parameter-value-in-bash)

Using a dictionary to select function to execute

Not proud of it, but:

def myMain(key):
def ExecP1():
pass
def ExecP2():
pass
def ExecP3():
pass
def ExecPn():
pass
locals()['Exec' + key]()

I do however recommend that you put those in a module/class whatever, this is truly horrible.


If you are willing to add a decorator for each function, you can define a decorator which adds each function to a dictionary:

def myMain(key):
tasks = {}

def task(task_fn):
tasks[task_fn.__name__] = task_fn

@task
def ExecP1():
print(1)
@task
def ExecP2():
print(2)
@task
def ExecP3():
print(3)
@task
def ExecPn():
print(4)

tasks['Exec' + key]()

Another option is to place all the functions under a class (or in a different module) and use getattr:

def myMain(key):
class Tasks:
def ExecP1():
print(1)
def ExecP2():
print(2)
def ExecP3():
print(3)
def ExecPn():
print(4)

task = getattr(Tasks, 'Exec' + key)
task()

Finding a key recursively in a dictionary

when you recurse, you need to return the result of _finditem

def _finditem(obj, key):
if key in obj: return obj[key]
for k, v in obj.items():
if isinstance(v,dict):
return _finditem(v, key) #added return statement

To fix the actual algorithm, you need to realize that _finditem returns None if it didn't find anything, so you need to check that explicitly to prevent an early return:

def _finditem(obj, key):
if key in obj: return obj[key]
for k, v in obj.items():
if isinstance(v,dict):
item = _finditem(v, key)
if item is not None:
return item

Of course, that will fail if you have None values in any of your dictionaries. In that case, you could set up a sentinel object() for this function and return that in the case that you don't find anything -- Then you can check against the sentinel to know if you found something or not.

How to add or increment a dictionary entry?

Use a defaultdict:

from collections import defaultdict

foo = defaultdict(int)
foo[bar] += 1

In Python >= 2.7, you also have a separate Counter class for these purposes. For Python 2.5 and 2.6, you can use its backported version.

How to search if dictionary value contains certain string with Python

I am a bit late, but another way is to use list comprehension and the any function, that takes an iterable and returns True whenever one element is True :

# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())

If you wanna count the number of element that have "Mary" in them, you can use sum():

# Number of sublists containing 'Mary'
print sum(any('Mary' in s for s in subList) for subList in myDict.values())

# Number of strings containing 'Mary'
print sum(sum('Mary' in s for s in subList) for subList in myDict.values())

From these methods, we can easily make functions to check which are the keys or values matching.

To get the keys containing 'Mary':

def matchingKeys(dictionary, searchString):
return [key for key,val in dictionary.items() if any(searchString in s for s in val)]

To get the sublists:

def matchingValues(dictionary, searchString):
return [val for val in dictionary.values() if any(searchString in s for s in val)]

To get the strings:

def matchingValues(dictionary, searchString):
return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]

To get both:

def matchingElements(dictionary, searchString):
return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}

And if you want to get only the strings containing "Mary", you can do a double list comprehension :

def matchingStrings(dictionary, searchString):
return [s for val in dictionary.values() for s in val if searchString in s]

How to initialize a dict with keys from a list and empty value in Python?

dict.fromkeys directly solves the problem:

>>> dict.fromkeys([1, 2, 3, 4])
{1: None, 2: None, 3: None, 4: None}

This is actually a classmethod, so it works for dict-subclasses (like collections.defaultdict) as well.

The optional second argument, which defaults to None, specifies the value to use for the keys. Note that the same object will be used for each key, which can cause problems with mutable values:

>>> x = dict.fromkeys([1, 2, 3, 4], [])
>>> x[1].append('test')
>>> x
{1: ['test'], 2: ['test'], 3: ['test'], 4: ['test']}


Related Topics



Leave a reply



Submit