定位一行文本中的单词
我在一个文本文件中找到了一行,如下所示:
FLAGS = WORD1 WORD2 WORD3
我正在阅读几个文件,其中单词数可以从 0 到最多 3 个不等。
我正在使用此代码:
flag_FLAG = 0
for i in range(len(materialfile)):
if "FLAG" in materialfile[i] and "=" in materialfile[i]:
line_FLAG = i
flag_FLAG = 1
if flag_FLAG == 1:
temp = materialfile[line_FLAG].split(" ")
for elem in temp:
if is_word(elem):
flags = str(elem)
不幸的是,这样我只能得到一个单词(最后一个)。 “is_word”是我创建的一个函数:
def is_word(s):
try:
str(s)
return True
except ValueError:
return False
我想将所有单词作为目标。 我希望我已经说清楚了。
I have identified a line in a text file that looks like this:
FLAGS = WORD1 WORD2 WORD3
I am reading several files in which the number of words can vary from 0 to a maximum of 3.
I'm using this code:
flag_FLAG = 0
for i in range(len(materialfile)):
if "FLAG" in materialfile[i] and "=" in materialfile[i]:
line_FLAG = i
flag_FLAG = 1
if flag_FLAG == 1:
temp = materialfile[line_FLAG].split(" ")
for elem in temp:
if is_word(elem):
flags = str(elem)
unfortunately this way I only get one word (the last one).
"is_word" is a function that i creat:
def is_word(s):
try:
str(s)
return True
except ValueError:
return False
I would like to get all the words as targets.
I hope I have been clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我以这种方式解决:
我不知道这是否是一种优雅的方式,但它似乎有效。谢谢
I solved in this way:
I don't know if this is an elegant way but it seems to work. Thanks
您想要一个嵌套循环,例如:
很难说这个确切的代码是否适用于您的实际文件,因为您没有提供示例文件,但希望这能让您指向正确的方向。
请注意,您的
is_word
函数不执行任何操作,因为它们已经是字符串,因此始终会作为无操作转换为str()
而不会引发异常。上述理解中的if flag
将过滤掉flag
中空的值(例如,如果您有像FLAGS =
这样的行)。You want a nested loop, e.g.:
Hard to say whether this exact code will work with your actual file, since you didn't provide a sample file, but hopefully this gets you pointed in the right direction.
Note that your
is_word
function does nothing since these are already strings and will hence always convert tostr()
as a no-op without raising an exception. Theif flag
in the above comprehension will filter out values offlag
that are empty (e.g. if you had a line likeFLAGS =
).