Python 如何检查文件的长度';s行只有2个字符?

Python 如何检查文件的长度';s行只有2个字符?,python,Python,如何检查文件行的长度是否只有2个字符?如果它的长度不是两个字符,我希望它打印出“2”逻辑:如果你想计算一个句子中有多少个单词,你必须计算有多少空格,并在其中添加1!! 基于您的问题,我附上一个示例代码,以帮助您计算行中的字数: 样本: with open(myfile, 'r') as textfile: encoder = {} decoder = {} for line in textfile: line = line.replace(' ', ''

如何检查文件行的长度是否只有2个字符?如果它的长度不是两个字符,我希望它打印出
“2”

逻辑:如果你想计算一个句子中有多少个单词,你必须计算有多少空格,并在其中添加1!! 基于您的问题,我附上一个示例代码,以帮助您计算行中的字数:

样本:

with open(myfile, 'r') as textfile:
    encoder = {}
    decoder = {}

    for line in textfile:
        line = line.replace(' ', '')
        if len(line) != 2:
            print("2")
            return

        if len(line) == 2:
            line = line.replace('', ' ')
            (key, value) = line.split()
            encoder[(key)] = value
            decoder[(value)] = key

            if key in encoder.keys():
                print("3")
现在,您可以轻松地比较变量字,并为每个条件返回相应的值

在本例中,您的优化代码如下所示:

line="this is sample line"
spaces = line.count(" ")
words = spaces+1
如果要打印(2)文件的一行有
len=2
,您可以像这样使用任何:

for line in textfile: 
    words = line.count(" ")+1
    if words != 2: 
        print("2") 
        return 
    else:
        #MoreLogics Here

如果要考虑字符
'\n'
'\t'
m,可以定义:
all\u lines=textfile.readlines()

使用此代码尝试实现什么?什么样的示例输入不起作用?这里不需要澄清,所以您的意思是,如果有两个以上的单词,程序将只打印2??是的,如果文件没有包含2个字符@Agent_orange的行,则只想打印“2”。我认为该行还将包含换行符(可能还有换行符)。你应该把这些从你的衣服上脱下来string@TeresaDavenport如果您给出一个示例,说明您的现有代码没有按照您的要求执行,这会有所帮助,显示:(a)输入行,(b)您想要的输出,(c)您当前获得的输出。如果您改为使用类似于
len(line.strip().split())
,则,这将忽略任何前导空格和尾随空格,然后将多个空格视为等同于单个空格。在计算字符串中的单词时,这更可能是预期的结果。
with open(myfile, 'r') as textfile:

    all_lines = textfile.read().splitlines()
    all_lines=[s.replace('\t', '') for s in all_lines]  #If you want to count '\t', you can erase this line
    if any(map(lambda x: len(x)!=2 , all_lines)):
        print('2')

    encoder = {}

    decoder = {}

    #....
    #Continue the rest of your script...