Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中将文本拆分为数组_Python_Arrays_Split - Fatal编程技术网

如何在python中将文本拆分为数组

如何在python中将文本拆分为数组,python,arrays,split,Python,Arrays,Split,我有一个符号为sss7775aaaa 4444a 555dussnss6 7djshs8 4ssssssssooo的文本文件,我只需要找到谁的单词,里面有数字 我认为程序应该以某种方式将所有由空格分隔的符号放入数组中,然后检查每个数组元素。但我不知道怎么做 谢谢。这里有一个方法: 使用openYOURFILE作为文件: 所有单词=file.read.split 包含数字的单词=[] 对于所有单词中的单词: 如果anychar.isdigit用于word中的字符: 包含数字的单词。追加单词 如果有

我有一个符号为sss7775aaaa 4444a 555dussnss6 7djshs8 4ssssssssooo的文本文件,我只需要找到谁的单词,里面有数字

我认为程序应该以某种方式将所有由空格分隔的符号放入数组中,然后检查每个数组元素。但我不知道怎么做

谢谢。

这里有一个方法:

使用openYOURFILE作为文件: 所有单词=file.read.split 包含数字的单词=[] 对于所有单词中的单词: 如果anychar.isdigit用于word中的字符: 包含数字的单词。追加单词
如果有字符串变量,可以使用str.split函数通过分隔符(默认为空格)分割数据。这将返回一个字符串列表

然后可以迭代列表中的每个项目,并使用正则表达式选择包含数字的项目

import re
def contains_num(inp):
    return bool(re.search(r'\d', inp)) # Search for string containing numbers

with open("symbols.txt") as f:
    symbols = f.read()

items = symbols.split()

ans = list(filter(contains_num, items))

您可以使用以下代码来实现您的想法:

# This list will store the words that contain numbers.
words_with_numbers = []

f = open('file.txt', 'r')
for line in f:
  line = line.strip()
  words = line.split(' ')
  for w in words:
    if any(c.isdigit() for c in w):
      words_with_numbers.append(w)
f.close()

参考:

快速一行,只是为了好玩,导入后重新:


按空格分割字符串,并按名称和数字进行筛选,将问题分为三部分。1读取python中的txt文件。2通过在空白处拆分,将字符串转换为数组。3迭代数组,也称为循环数组,然后过滤使用if-else子句并将其存储在新数组中。这是基于对类似问题的回答。归功于Fourtheye:您需要将单词附加到包含数字的单词列表中,而不是将单词连接到它。您需要append+=将字符串中的每个字符作为新元素添加到字符串中。我刚刚测试并实现了它。谢谢你。回过头来看,这似乎是合乎逻辑的,因为字符串是一个Iterable。使用break after.appendw可以减少检查的字符数。
list(filter(lambda w: re.search(r'\d', w), open("your-file.txt").read().split()))