简体   繁体   English

Python:如何根据字符串中单词的数量将字符串拆分为变量?

[英]Python: How to split a string into variables according to the amount of the words in the string?

I have a string like: 我有一个像这样的字符串:

text = The Black Cat is running 

and I want to split the text into words and create a variable for each word without setting it manually. 我想将文本拆分为单词,并为每个单词创建一个变量,而无需手动设置。 some thing like this: 像这样的事情:

one="The"
two="black"
three="Cat"
four="is"
five="running"

but if there is a different string with more or fewer words it will create an amount of variables according to the amount of words; 但是,如果存在一个包含更多或更少单词的不同字符串,则会根据单词数量创建一定数量的变量; for example, if there are seven words it will create seven variables. 例如,如果有七个单词,它将创建七个变量。

You can have a dictionary and create the variables on the fly for each value in text : 您可以拥有一个字典并为text每个值即时创建变量:

So, you don't have to worry about larger strings. 因此,您不必担心较大的字符串。 It will create n number of variables depending upon its length. 它将根据其长度创建n个变量。

In [2355]: d = {}
In [2357]: for c,i in enumerate(text.split()):
      ...:     d['var{}'.format(c)] = i
      ...:     
      ...:     

In [2358]: d
Out[2358]: 
{'var0': 'The',
 'var1': 'Black',
 'var2': 'Cat',
 'var3': 'is',
 'var4': 'running'}

Then, you can access the dictionary like below: 然后,您可以如下访问字典:

In [2362]: for key in d.keys():
      ...:     print(key,d[key])
      ...:     
('var4', 'running')
('var1', 'Black')
('var0', 'The')
('var3', 'is')
('var2', 'Cat')

Just unpack the values, for example: 只需解压缩值,例如:

text = "The Black Cat is running"

one, two, three, four, five, *_ = l = text.split()

for n in l:
  print(n)

Notice the usage of *_ in case the resulting split has more words than desired. 请注意*_的用法,以防产生的拆分词多于所需的词数。 In case it has less it will always fail. 万一它少了,它将总是失败。

Here you have the live example 这里有现场示例

suppose we have this string 假设我们有这个字符串

str = "The Black Cat is running"

then we need to split it to get all array elements of the string as: 那么我们需要将其拆分为字符串的所有数组元素,如下所示:

str_arr = str.split(" ") 

str_arr = ['The', 'Black', 'Cat', 'is', 'running']

To persist the dynamic variable's value, we can use Hash: 要保留动态变量的值,可以使用哈希:

 mydict = {}

And then we need to iterate the array and assign the element to the unique variable as below: 然后,我们需要迭代数组并将元素分配给唯一变量,如下所示:

for index in range(len(str_arr)):
  mydict["var_%d" %index] = str_arr[index]
  print "var_%d : " %index + str_arr[index]

which will give the output as: 输出为:

var_0 : The

var_1 : Black

var_2 : Cat

var_3 : is

var_4 : running

And to print Hash, we can write: 并打印哈希,我们可以写:

print mydict
{'var_0': 'The', 'var_1': 'Black', 'var_2': 'Cat', 'var_3': 'is', 'var_4': 'running'}

Hope, this will provide some hint to write to your next logic.. 希望,这将为您编写下一个逻辑提供一些提示。

I read this as two different questions. 我将其视为两个不同的问题。

1. Split each word in the string into a separate variable 1.将字符串中的每个单词拆分为一个单独的变量

You can do this very simply with the .split() method for strings. 您可以使用.split()方法非常简单地执行此操作。 As answered above 如上所述

text = "The Black Cat is running"
one, two, three, four, five, *_ = l = text.split()

2. Count the letters of each word 2.计算每个单词的字母

One way that you could approach this is to first sort the words by the number of letters they have, and then second to assign them to proper variables. 您可以采用的一种方法是,首先按单词的字母数对其进行排序,然后再将它们分配给适当的变量。 For instance 例如

def count_letters_in_each_word(text):
    word_counts = {len(word): word for word in text.split(' ')}
    max_length = max(word_counts.keys())
    return [word_counts.get(cnt) for cnt in range(1, max_length+1)]

text = 'The Black cat is flopping around'
one, two, three, four, five, six, seven, eight = count_letters_in_each_word(text)
print(one)
> None
print(five)
> "Black"
print(seven)
> None
print(eight)
> "flopping"

# or, if you only want short words
one, two, *_ = count_letters_in_each_word(text)

The best way to deal this problem would be to use list of dict instead. 解决此问题的最佳方法是改用dict list But for some reasons, if you want to create variables as you mentioned then this might help 但是由于某些原因,如果您要像前面提到的那样创建变量,那么这可能会有所帮助

text = "The Black Cat is running "
text=text.strip().split(" ")

for i,j in enumerate(text,1):
    locals()['var'+str(i)]=j # create variable as var1='The' and so on in local scope

Trying accessing the variables 尝试访问变量

print(var1,var2,var3,var4,var5)

Output 产量

('The', 'Black', 'Cat', 'is', 'running')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM