The code is in C programming language pls convert it into python. Thanks.
Program -->
#include <stdio.h>
#include <stdlib.h>
void main()
{
//declare variables
FILE *fileptr;
char filename[15];
char charRead;
char filedata[200],searchString[50];
int i=0,j=0,countNoOfWord=0,count=0;
//enter the filename to be opened
printf("Enter the filename to be opened \n");
scanf("%s", filename);
/* open the file for reading */
fileptr = fopen(filename, "r");
//check file exit
if (fileptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
charRead = fgetc(fileptr);
//read the string from file
while (charRead != EOF)
{ filedata[i]=charRead;//store the file data in a string filedata variable
printf ("%c", charRead);
charRead = fgetc(fileptr);//get data from file
i++;
}
//count the total no of word in a file
for (j = 0;filedata[j] != '\0';j++)
{
if (filedata[j] == ' ')
countNoOfWord++;
}
strlwr(filedata);//convert string into lower case
printf("\nnumber of words in given string are: %d\n", countNoOfWord );
fclose(fileptr);
//enter the word u want to count
printf("Enter word to count: \n");
scanf("%s", searchString);
//call function countOccuranceOfWord to count the word which return integer of no of words
count = countOccuranceOfWord(filedata, searchString);
printf("Total occurrences of '%s': %d \n", searchString, count);
//write into file output.txt
fileptr = fopen("output.txt", "w");
if(fileptr == NULL)
{
printf("Error!");
exit(1);
}
char sentence1[50]="Total no. of words";
char sentence2[50]="Total occurrences of ";
//writing into output.txt
fprintf(fileptr,"%s %d %s %s %d", sentence1,(countNoOfWord),sentence2,searchString,count);
fclose(fileptr);//close fileptr
}
//function to countOccurance of word
int countOccuranceOfWord(char * str, char * toSearch)
{
int i, j, found, count;
int stringLen, searchLen;
stringLen = strlen(str); // length of string
searchLen = strlen(toSearch); // length of word to be searched
count = 0;
for(i=0; i <= stringLen-searchLen; i++)
{
/* Match word with string */
found = 1;
for(j=0; j<searchLen; j++)
{
if(str[i + j] != toSearch[j])
{
found = 0;
break;
}
}
if(found == 1)
{
count++;
}
}
return count;
}
filename = input("enter the file name:")
f = open(filename,'r')
paragraph = f.read()
countnowords = 0
for i in range(0,len(paragraph)):
if(paragraph[i] == ' ' or paragraph[i] == '.' or
paragraph[i] == '\n'):
countnowords += 1
count_string = input("enter the string to count:")
no_of_occurences = paragraph.count(count_string)
f.close()
f = open("output.txt","w")
f.write("Total no of words : {} \n Total no of occurences of {} is
{}".format(countnowords,count_string,no_of_occurences))
f.close()
If you have any doubts please comment and please don't dislike.
Get Answers For Free
Most questions answered within 1 hours.