Number of characters without spaces in a file
Solvedarscy Posted messages 196 Status Member -
4 answers
-
Hello,
Or you can simply do it like this:
nb_spaces = line.count(' ') nb_car += (len(line) - nb_spaces) -
Hello
You need to clarify what you mean by space, because in Python a.isspace() returns True if a is a space, a tab, or a newline.
If you want to ignore all characters that fall into this category:
def count_non_space_chars(s: str) -> int: return sum( 1 for a in s if not a.isspace() )
If you only want to ignore the character ' ':
def count_non_space_chars(s: str) -> int: return sum( 1 for a in s if a != ' ' )
Once this choice is made, to use the function on a file, say /etc/motd:
filename = "/etc/motd" with open(filename, "r") as f: print(count_non_space_chars(f.read()))
Good luck
-
Hello,
Instead of posting an image, it's better to display your code here
instructions:
https://codes-sources.commentcamarche.net/faq/11288-poster-un-extrait-de-code
Visually, it should look like this:
for k in range(10): print(k)
Aside from that, there is a Python method applicable to strings that allows you to count the occurrences
of a given character (here the space, that is)
And then, we do this:
nb_car += (len(line) - nb_spaces_in_the_line)
-
with open("devoirnsi.txt","r") as fic: nb_mot=0 nb_car=0 nb_ligne=0 nb_space=0 nb_voy=0 nb_cons=0 contenu=[] for ligne in fic: nb_ligne+=1 contenu+=ligne.split() nb_car+=len(ligne) print("The number of lines in this text is:", nb_ligne) print("The number of characters in this text is:", nb_car-nb_space) print("The number of words in this text is:", len(contenu)) print("The number of vowels in this text is:", nb_voy) print("The number of consonants in this text is:", nb_cons)-
Good evening,
If you don't see how to not take spaces into account, it means you don't know what you have coded :-(
- How does the split function work?
- What is the point of reducing the content of a line to an array?When you are able to answer these two points, you should be able to make significant progress on your issue (or even solve your question, actually).
On the other hand, if you wanted to count the number of spaces (see your variable 'nb_space'), you would benefit from proceeding differently, for example by searching for the space character _ ' '_ in each line or in a concatenation of your different lines.
Keep us updated on your progress
-
