I'm working with a text file that looks like this; (The words are in Swedish)
['1', 'Denna', '_', 'DET', 'DT', 'UTR|SIN|DEF', '2', 'DT', '_', '_\n']
['2', 'predestination', '_', 'NOUN', 'NN', 'UTR|SIN|IND|NOM', '7', 'SS', '_', '_\n']
['3', 'till', '_', 'ADP', 'PP', '_', '2', 'ET', '_', '_\n']
['4', 'en', '_', 'DET', 'DT', 'UTR|SIN|IND', '6', 'DT', '_', '_\n']
.....
There are about 500 sentences of various lenghts; each line describes one word. The first list element gives the word's position in the sentence.
I need my program to make a nested list from the entries for each sentence (one sub-list for each sentence). Every new sentence starts with position '1', and they are separated by empty lines. At the moment all my lines are in one list.
I would like to do something like:
l = []
for line in list:
if line[0] == '1':
l.append(line)
... then append every line that follows until it reaches '1' again, where I start with a new sub-list.
Some ides on how to do it? How could I make this recursive?
This is not a naturally recursive process; it's iterative. A simple loop will do the job.
alla = []
forst = True
for line in list:
if line[1] == '1':
# ny mening
if not forst:
alla.append(mening)
forst = False
mening = []
mening.append(line)
Since the trigger for each append is the start of the sentence, you still have one sentence left to add. I'll leave that part for you to do. :-)
Related
Please help me out I tried doing this but I don't know what's wrong with my code, it didn't work.
msgs_up=message.content.upper
msg_count=msgs_up.count(msgs_up,0,200)
if ( msg_count >= 4 ):
await message.channel.send('Woah woah. stop the cap')
You can use regular expressions to find the number of capital letters in a string.
import re
regex = "[A-Z]" # Matches only capital letters
string1 = "Not too many caps here"
string2 = "FULL of CAPS"
Use the findall method to get all matches
>>> re.findall(regex, string1)
['N']
>>> re.findall(regex, string2)
['F', 'U', 'L', 'L', 'C', 'A', 'P', 'S']
This returns a list containing all matches. You can now check if the string contains more than four capital letters by checking if the length of the list is greater than 4.
However, note that it is often better to check if a percentage of letters is capital rather than a fixed amount.
>>> string3 = "This string might appear to not contain too many Capital Letters. But, it still triggers the response since the number of Capital Letters is greater than 4.
>>> re.findall(regex, string3)
['T', 'C', 'L', 'B', 'C', 'L'] # 6 capital letters
I have absolutely no clue where to look for.. I have 2 arrays in jQuery and I want to combine the values together. As in: first value array one with first value array 2..
I have 2 arrays, example:
$arrayOne = 'A', 'B', 'C', 'D'
$arrayTwo = '1', '2', '3', '4'
I want to combine these and get the following output
'A': '1',
'B': '2',
'C': '3',
'D': '4',
Any help would be very much appreciated!
Danny
Approach: Loop over the array whose value you want as a key & then push one by one key value pair objects into a map object which is has to declare above the loop.
Note: Both arrays should have the same number of elements.
Code:
$arrayOne = ['A', 'B', 'C', 'D']
$arrayTwo = ['1', '2', '3', '4']
var arrayToMap = new Object(); // or var map = {};
$arrayOne.forEach(function( value, index ) {
arrayToMap[value] = $arrayTwo[index];
});
console.log(arrayToMap);
Output:
{A: "1", B: "2", C: "3", D: "4"}
You can refer the following link if you are new to the array list + loops:
https://api.jquery.com/jquery.each/
I have an array that contains string elements:
farm = np.array(garden)
leads to this:
[['F' 'F' 'W' 'W']
['F' '_' '_' 'W']
['G' '_' '_' 'J']
['G' 'G' 'J' 'J']]
I want to count how many times lets say 'F' appears, is there a simple way to do this? This is a small version of the bigger array that I will be working on
EDIT:
Lists have a count method. So your new and improved pythonic code is
D= sum([i.count("F") for i in listX])
Well you can make a function, that
Checks if the parameter passed to it is in the array. You can even use list comprehensions. For example
F = sum([sum([1 for i in j if i=="f"]) for j in listX])
Michael's solution is the most "pythonic", but I wanted to offer an alternative solution using simpler constructs, in case you're just learning:
lst = []
lst.append(['F', 'F', 'W', 'W'])
lst.append(['F', '_', '_', 'W'])
lst.append(['G', '_', '_', 'J'])
lst.append(['G', 'G', 'J', 'J'])
numFs = 0
# Look at each sublist
for sublist in lst:
# Look at each element within the sublist
for s in sublist:
# If the element is an 'F', add 1 to the number of Fs
if s == 'F':
numFs += 1
print(numFs)
You could also try to reduce and join the elements of the arrays into a string and then count, like so:
from functools import reduce
a = [['F' 'F' 'W' 'W'], ['F' '_' '_' 'W'], ['G' '_' '_' 'J'], ['G' 'G' 'J' 'J']]
c = ''.join(reduce(list.__add__, a)).count('F')
print(c)
When executed, this code prints:
3
I'm trying to debug a program in ruby that is meant to compute and print the average length of words in an array.
words = ['Four', 'score', 'and', 'seven', 'years', 'ago', 'our', 'fathers', 'brought', 'forth', 'on', 'this', 'continent', 'a', 'new', 'nation', 'conceived', 'in', 'Liberty', 'and', 'dedicated', 'to', 'the', 'proposition', 'that', 'all', 'men', 'are', 'created', 'equal']
word_lengths = Array.new
words.each do |word|
word_lengths << word_to.s
end
sum = 0
word_lengths.each do |word_length|
sum += word_length
end
average = sum.to_s/length.size
puts "The average is " + average.to_s
Obviously, the code is not working. When I run the program, I receive an error message that says the string '+' can't be coerced into fixnum (typeerror).
What do I do no make the code compute the average length of the strings in the array?
Try:
words.join.length.to_f / words.length
Explanation:
This takes advantage of chaining methods together. First, words.join gives a string of all the characters from the array:
'Fourscoreandsevenyearsagoourfathersbroughtforthonthiscontinentanewnationconcei
vedinLibertyanddedicatedtothepropositionthatallmenarecreatedequal'
We then we apply length.to_f giving the length as a float (using a float ensures an accurate final result):
143.0
We then divide the above using / words.length:
4.766666666666667
Try this.
words = ['Four', 'score', 'and', 'seven', 'years', 'ago', 'our', 'fathers',
'brought', 'forth', 'on', 'this', 'continent', 'a', 'new', 'nation',
'conceived', 'in', 'Liberty', 'and', 'dedicated', 'to', 'the', 'proposition',
'that', 'all', 'men', 'are', 'created', 'equal']
sum = 0
words.each do |word|
sum += word.length
end
average = sum.to_i/words.size
puts "The average is " + average.to_s
You don't have to have a separate word_lengths variable to keep all the sizes of words in words array. Without looping through the word_lengths array you can merge both loops into one loop as I have given in the post.
The way you're getting the length of the word is wrong. Use word.length. See here.
I want to write a line of code that checks if the iteration i==someValue and the next iteration i==anotherValue then write a line of code in the loop.
E.g
for line in file:
if line[1]=='A' and if next(line[1]) == 'B'
print("do something here")
How can I go about achieving this?
Thanks!
One solution is to store the value that you want for the first line as a control value. If the next line does not have the correct value - the control value is cleared. For example like:
file = ['A', 'A', 'B', 'C', 'A', 'C', 'B']
control_value = ''
for line in file:
if line == 'A':
control_value = line
continue
if line == 'B' and control_value == 'A':
print('Do something here')
control_value = ''
Any values except 'A' will reset the control_value.